jquery.validate.js作为前端开发的利器之一,深受广大前端工程师的喜爱,然而很多人却不善于利用remote,下面,对,就是下面,下面还有,我们来看看如何更合理的利用jQuery validate的remote。
介绍的内容主要有两点:
- 传统情况下,我们习惯使用addMethod方法为某个input提供后端验证机制,而不善于使用remote。
- 为remote方法提供附加的动态参数,比如你要验证昵称有没有被使用,你需要传递一下用户id。
第一步:下载jquery.validate.js,并使用下面的语句将其加入到项目中
<script src="js/jquery.validate.js" type="text/javascript"></script>
remote: function( value, element, param ) { if ( this.optional(element) ) { return "dependency-mismatch"; } // 已经验证过了,会从这里面取 var previous = this.previousValue(element); if (!this.settings.messages[element.name] ) { this.settings.messages[element.name] = {}; } previous.originalMessage = this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; param = typeof param === "string" && {url:param} || param; if ( previous.old === value ) { return previous.valid; } previous.old = value; var validator = this; this.startRequest(element); var data = {}; data[element.name] = value; // 设置附加参数 if($(element).attr("params")){ // 通过eval方法将附加参数转换为object对象 var params = eval('(' + $(element).attr("params") + ')'); for(var p in params){ data[p] = params[p]; } } $.ajax($.extend(true, { url: param,// 传递的后台url,来进行数据验证 mode: "abort", type: "post", port: "validate" + element.name, dataType: "json", data: data,//传递的参数为对应intput标签对应name和value值 success: function( response ) {//response为后台返回数据,错误的时候返回错误提示信息,正确的时候返回true validator.settings.messages[element.name].remote = previous.originalMessage; var valid = response === true || response === "true";//如果返回true,则会进入到if语句,错误提示消失 if ( valid ) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); delete validator.invalid[element.name]; validator.showErrors(); } else { var errors = {}; var message = response || validator.defaultMessage( element, "remote" );//如果后台返回有错误提示信息,则不会取默认显示信息 errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; validator.invalid[element.name] = true; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return "pending"; }
<input type="text" class="required alphanumeric" remote="${ctx}/jade/checkCodeIsExist.do" name="code"/>
<input name="marketname" id="marketname" class="required" maxlength="50" params="{oldname:'${market.marketname}'}" type="text" value="${market.marketname}" remote="${ctx}/stocks_config/marketnameCheck.do" maxlength="10">
@RequestMapping(value = "checkCodeIsExist") public void checkCodeIsExist(HttpServletRequest request, HttpServletResponse reponse) throws Exception { <span style="white-space:pre"> </span>Jadeinfo jadeinfo = this.jadeinfoDAO.selectByCodeKey(StrUtil.getUTF8String(request.getParameter("code"))); if (jadeinfo != null && jadeinfo.getDeleteflag() == 0) { out("商品代码已存在!", reponse); } else { out(true, reponse); } }
jQuery.validator.addMethod("codeCheck", function(value, element) { $.ajax({ url : common.ctx + "/jade/jade.do?action=checkCode",// 请求的URL data : { code : value },// 传递给action的参数{dictTypeId:'PC_STATE'} async : false, // 改异步为同步 dataType : 'json', success : function(records) { $("#checkcode").val(records); } }); var result = $("#checkcode").val(); if (result == "true") { return this.optional(element) || true; } else { return this.optional(element) || false; } }),