jquery validationengine 异步验证问题

jquery validationengine 的基本功能和使用我在此就不多讲了,大家可以参考

下载:https://github.com/posabsolute/jQuery-Validation-Engine

文档:http://posabsolute.github.io/jQuery-Validation-Engine/

我使用的版本为:jQuery.validationEngine v2.6.1

在使用异步验证的时候,对于多个字段验证,我做了扩展,在全局参数出,加了一个字段,ajaxField,在点击提交按钮的时候,对该字段进行处理,因为点击提交按钮,作者认为没有必要验证ajax异步验证字段,忽略了这些字段的验证,但是其实需要验证,该验证组件原理是如果该字段验证了,对该字段进行标记,所以对_checkAjaxFieldStatus方法进行改造,使其可以满足多个字段。

1.JS:

function ajaxValidationCallback(status, form, json, options){
       
  }
  jQuery(document).ready(function(){
   $.validationEngineLanguage.allRules["ajaxFunction"] = {
              "url": "sys/function/validate"
   };
   jQuery("#formFunID").validationEngine({
    ajaxField:['fCode','fCaption'],
    ajaxFormValidation: true,
    onAjaxFormComplete: ajaxValidationCallback
   });

2.表单:

<form id="formFunID"  method="post" action="sys/function/create" style="width:100%">
 <ul style="clear:both; padding-top:4px; margin-top:0px;">
  <li><label><i class="biaoji">*</i>功能名称:</label><input id="fCaption" class="validate[required,ajax[ajaxFunction]] text-input" type="text" name="caption" /></li>
  <li><label><i class="biaoji">*</i>功能编码:</label> <input id="fCode" class="validate[required,ajax[ajaxFunction]] text-input" type="text" name="functioncode" /></li>
 </ul>
 <div id="split">
 <input id="cancel_btn" class="submit" type="button" value="取消"/>
 <input id="submit_add" class="submit" type="submit" value="提交"/>
 </div>
 </form>

3.验证

@RequestMapping(value="/sys/function/validate",produces="text/plain;charset=UTF-8")
 @ResponseBody
 public String validateFunctionCode(HttpServletRequest request,HttpServletResponse response) throws IOException{
  //页面中要验证的输入框中的值,接收参数值必须是fieldValue,组件内设置
  String functionCode = request.getParameter("fieldValue");
  //页面中要验证的输入框的ID,接收参数必须是fieldId,组件内设置
  String fieldId = request.getParameter("fieldId");
  System.out.println(request.getParameter("name"));
  boolean isExists = false;
  String msgErr = "";
  String msgRig = "";
  if (fieldId.equals("fCode")){
   msgErr = "功能编码已存在";
   msgRig = "功能编码可用";
   SysFunction function = new SysFunction();
   function.setFunctioncode(functionCode);
   isExists = functionService.selectIsExistsFunction(function);
  } else if (fieldId.equals("fCaption")){
   msgErr = "功能名称已存在";
   msgRig = "功能名称可用";
   SysFunction function = new SysFunction();
   function.setCaption(functionCode);
   isExists = functionService.selectIsExistsFunction(function);
  }
  String out = "";
  if (isExists) {
   out = (new AjaxValidationFormResponse(fieldId,"false",msgErr)).toValidation();
  } else {
   out = (new AjaxValidationFormResponse(fieldId,"true",msgRig)).toValidation();
  }

//返回json格式必须是[字段ID,布尔类型,显示信息]这种格式,因为在组件内解析的时候是这种格式
  return out;
 }

4.转JSON

package com.cnpc.oms.utils.validate;

import java.io.Serializable;

/**
 * 前台页面提示
 * @author 张昭
 *
 */
public class AjaxValidationFormResponse implements Serializable{
 /**
  *
  */
 private static final long serialVersionUID = 1L;

 // the html field id
 private String id;

 // true, the field is valid : the client logic displays a green prompt
 // false, the field is invalid : the client logic displays a red prompt
 private String status;

 // either the string to display in the prompt or an error
 // selector to pick the error message from the translation.js
 private String message;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getStatus() {
  return status;
 }

 public void setStatus(String status) {
  this.status = status;
 }
 

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }
 /**
  * 验证框架使用
  * @param fieldId
  * @param s
  * @param msg
  */
 public AjaxValidationFormResponse(String fieldId, String s, String msg) {
  id = fieldId;
  status = s;
  message = msg;
 }
 /**
  * 提示使用
  * @param msg
  */
 public AjaxValidationFormResponse(String msg) {
  message = msg;
 }
 /**
  * 验证框架使用
  * @return
    @author 张昭
  */
 public String toValidation() {
  return "[\"" + id + "\","+status+",\"" + message + "\"]";
 }
 /***
  * 前台提示使用
  * @return
    @author 张昭
  */
 public String toMessage(){
  return "{\"msg\":\""+message+"\"}";
 }
}
5.jquery.validationEngine.js

修改:

$.validationEngine = {
  fieldIdCounter : 0,
  defaults : {

                 ajaxField:"",

                 ......其他原有字段

}  

}

 

_checkAjaxFieldStatus : function(fieldid, options) {
   if (fieldid instanceof Array){
    var fStatus = false;
    for (var i=0;i<fieldid.length;i++){
     if (options.ajaxValidCache[fieldid[i]] == true){
      fStatus = true;
     }else{
      fStatus = false;
      break;
     }
    }
    return fStatus;
   }else{
    return options.ajaxValidCache[fieldid] == true;
   }
  }

 

6.jquery.validationEngine.js

修改_onSubmitEvent方法:

_onSubmitEvent : function() {
   var form = $(this);
   var options = form.data('jqv');
   // check if it is trigger from skipped button
   if (form.data("jqv_submitButton")) {
    var submitButton = $("#" + form.data("jqv_submitButton"));
    if (submitButton) {
     if (submitButton.length > 0) {
      if (submitButton.hasClass("validate-skip")
        || submitButton
          .attr("data-validation-engine-skip") == "true")

       return true;
     }
    }
   }
   options.eventTrigger = "submit";
   // validate each field
   // (- skip field ajax validation, not necessary IF we will perform
   // an ajax form validation)
   var r = methods._validateFields(form);
   if (r && options.ajaxFormValidation) {
    if (options.ajaxField != null && options.ajaxField != "") {
     if (!methods._checkAjaxFieldStatus(options.ajaxField, options)) {
      return false;
     }else{
      methods._validateFormWithAjax(form, options);
      // cancel form auto-submission - process with async call
      // onAjaxFormComplete
      return false;
     }
    }else{
     methods._validateFormWithAjax(form, options);
     // cancel form auto-submission - process with async call
     // onAjaxFormComplete
     return false;
    }
   }
   if (options.onValidationComplete) {
    // !! ensures that an undefined return is interpreted as return
    // false but allows a onValidationComplete() to possibly return
    // true and have form continue processing
    return !!options.onValidationComplete(form, r);
   }
   /*
    * if (r && !methods._checkAjaxStatus(options)) { return false; }
    *
    * if(options.onValidationComplete) {
    * options.onValidationComplete(form, r); return false; }
    */
   
   return r;
  }

 

你可能感兴趣的:(jquery validationengine 异步验证问题)