2011-12-19 93 views
1

我写了一个函数来验证jQuery中一个表单中的一个输入字段。但我的表单中有两个额外的文本字段。我不确定添加其他规则给他们的方法。这是我到目前为止所尝试过的。在JQuery中验证输入字段

$(document).ready(function() { 
$(document).ready(function() { 
jQuery.validator.addMethod("url_validation", function (value, element) { 
return this.optional(element) || /^(([http|https|HTTPS|HTTP]+:\/\/))?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)[email protected])?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/i.test(value); 
}, "error"); 

$('#myform').validate({ 
    /** this section is working */ 
    rules: { 
     text_name: { 
      required: true, 
      url_validation: true, 
      maxlength: 2000 
     } 
    }, 
    messages: { 
     text_name: { 
      required: "Please specify a URL", 
      url_validation: "The domain you have entered is not a valid domain or sub domain name. Please try again.", 
      maxlength: "You have exceeded the maximum length" 
     } 
    } 
    /**********************************************************/ 
    /*this is where i tried to add other rules to two of my other textboxes*/ 
    rules: { 
     text_name2: { 
      required: true, 
      url_validation: true, 
      maxlength: 2000 
     } 
    }, 
    messages: { 
     text_name2: { 
      required: "Please specify a URL", 
      url_validation: "The domain you have entered is not a valid domain or sub domain name. Please try again.", 
      maxlength: "You have exceeded the maximum length" 
     } 
    } 
    /*above thing is not working*/ 

}); 

在我的HTML还有其他两个文本框我需要验证。如何执行此任务?

回答

2

验证插件采用rulesmessages作为参数的选项对象。填满它们,但不要指定rulesmessages对象。

它应该是:

$('#myform').validate({ 
    rules: { 
     text_name: { 
      ... 
     }, 
     text_name2: { 
      ... 
     } 
    }, 
    messages: { 
     text_name: { 
      ... 
     }, 
     text_name2: { 
      ... 
     } 
    } 
});