日期:2014-05-16 浏览次数:20630 次
validationEngine v2.0进行了重写,变化很大。
?
首先说一下整个表单验证,使用简单的一行代码就能完成:
$("#form.id").validationEngine('validate');
这是我之前用的验证代码:
var success=true;
$(formid+" :text,"+formid+" select,"+formid+" textarea").each(function(i,input){
? if($.validationEngine.loadValidation("#"+$(input).attr('id'))){
? ?success=false;
??}
});
是挨个验证的,当然现在也可以挨个验证:
$("#form.id").validationEngine('validateField', "比如一个INPUT的ID");
?
?
下面是自己使用AJAX验证的一点经验:
?
1.和旧版本一样,也是在域的class属性中添加ajax[XXXX],XXXX是自定义的验证规则。
2.规则与旧版本就有区别了:
"ajaxUserCall": {
??? "url": "ajaxValidateFieldUser",
??? "extraData": "name=eric",
??? "extraDataDynamic": ['#user_id', '#user_email'],
??? "alertText": "* This user is already taken",
??? "alertTextOk": "All good!",
??? "alertTextLoad": "* Validating, please wait"
}
3.接下来这部分是我修改的两处validationEngine源代码,因为我认为这部分不适合使用struts2。
if (!options.isError) { alert(extraDataDynamic); $.ajax({ type: "GET", url: rule.url, cache: false, dataType: "json", data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.val() + "&extraData=" + extraData + "&" + extraDataDynamic, field: field, rule: rule, methods: methods, options: options, beforeSend: function() { // build the loading prompt var loadingText = rule.alertTextLoad; if (loadingText) methods._showPrompt(field, loadingText, "load", true, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json.validateReturn[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { var status = json.validateReturn[1]; // read the optional msg from the server var msg = json.validateReturn[2]; if (!status) { // Houston we got a problem - display an red prompt options.ajaxValidCache[errorFieldId] = false; options.isError = true; // resolve the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) msg = txt; } } else msg = rule.alertText; methods._showPrompt(errorField, msg, "", true, options); } else { if (options.ajaxValidCache[errorFieldId] !== undefined) options.ajaxValidCache[errorFieldId] = true; // resolves the msg prompt if(msg) {