validate是一个基于Jquery的表单验证插件,利用他的remote可以用来自定义远程验证,最近在项目中用到这个,但是在这当中遇到的几个问题,感觉让人很误解,下面我们来看例子。
这是要验证的表单:
- <form id="frm" name="frm" class="validateform">
- <p><label for="pinm86"> 品名:</label><input type="text" id="pinm86" name="pinm86" /></p>
- <p><label for="fangjianid78">房间号:</label><input type="text" id="fangjianid78" name="fangjianid78" /></p>
- </form>
这里我要验证品名的唯一性,如果输入品名重复就提示
下面是JS代码
- <script type="text/javascript">
- jQuery(document).ready(function($){
- $(".validateform").validate({
- rules:{
- pinm86:{
- required:true,
- remote:{
- url: "validateSbSbinfoData.action", //后台处理程序
- type: "get", //数据发送方式
- dataType: "json", //接受数据格式
- data: { //要传递的数据
- pinm86: function() {
- return $("#pinm86").val();
- }
- }
- }
- }
- },
- messages:{
- pinm86:{
- remote:"品名已经存在!"
- } }
- });
- });
- </script>
很多网上文章在只提到remote接受Json格式数据,然后就没有了,其实remote接受的返回值只要true和false即可,通过查看源代码可以发现,remote通过返回的false和true来判断的,那么就是说你后台程序只要返回true和false值,这点让我误解了许久。由于项目用到了Struts2,这是struts的配置文件,相信你不会陌生吧:
- <package name="json_sbSbinfo" extends="json-default">
- <action name="validateSbSbinfoData" class="sbSbinfoAction" method="validateData">
- <result name="success" type="json">
- <param name="defaultEncoding">UTF-8</param>
- <param name="root">resstr</param> 这里的resstr 就是Action里面对应的属性值
- </result>
- <result name="error" type="json"><param name="defaultEncoding">UTF-8</param></result>
- </action>
- </package>
这边有俩点要注意一下:1.因为Action里面要返回Json数据格式所以<package name="json_sbSbinfo" extends="json-default"> 这里的extends是“json-default” 而不是以往的“struts-default”。
2.要加上这个参数 <param name="root">resstr</param> 这里的resstr 就是Action里面对应的属性值
下面是sbSbinfoAction
- public class SbSbinfoAction extends ActionSupport implements ServletRequestAware,SessionAware {
- private boolean resstr;
- public String validateData()
- {
- String result = ERROR;
- String vcpinm=(String)this.request.getParameter("pinm86");
- Map map= new HashMap();
- map= sbSbinfoService.validateData(vcpinm);
- Object dd=map.get("n");
- String s=dd.toString();
- if(s.equals("0"))
- {this.resstr=true;}
- else
- {this.resstr=false;
- }
- result= SUCCESS;
- return result;
- }
- @JSON(serialize=false)
- public SbSbinfoService getSbSbinfoService() {
- return sbSbinfoService;
- }
- public boolean getResstr() {
- return resstr;
- }
- public void setResstr(boolean resstr) {
- this.resstr = resstr;
- }
- }
这里涉及到Json数据格式转换的问题,将在未来的相关文章里涉及到,希望这篇文章帮助到你哦!
本文来自鲜橙吧 原文地址:http://www.xianchengba.com/230.html