jQuery validate: How to add a rule for regular expression validation?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expression validator. I want to be able to do something like this:
Additionally, it looks like there is a file called additional-methods.js that contains the method "pattern", which can be a RegExp when created using the method without quotes.
$.validator.addMethod('postalCode', function (value) { return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); }, 'Please enter a valid US or Canadian postal code.');
I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.
回答5:
No reason to define the regex as a string.
$.validator.addMethod( "regex", function(value, element, regexp) { var check = false; return this.optional(element) || regexp.test(value); }, "Please check your input." );
Resetting the lastIndex property is necessary when the g-flag is set on the RegExp object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.
Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:
function validateSignup() { $.validator.addMethod( "regex", function(value, element, regexp) { if (regexp.constructor != RegExp) regexp = new RegExp(regexp); else if (regexp.global) regexp.lastIndex = 0; return this.optional(element) || regexp.test(value); }, "Please check your input." ); $('#signupForm').validate( { onkeyup : false, errorClass: "req_mess", ignore: ":hidden", validClass: "signup_valid_class", errorClass: "signup_error_class", rules: { email: { required: true, email: true, regex: /^[A-Za-z0-9_]+\@[A-Za-z0-9_]+\.[A-Za-z0-9_]+/, }, userId: { required: true, minlength: 6, maxlength: 15, regex: /^[A-Za-z0-9_]{6,15}$/, }, phoneNum: { required: true, regex: /^[+-]{1}[0-9]{1,3}\-[0-9]{10}$/, }, }, messages: { email: { required: 'You must enter a email', regex: 'Please enter a valid email without spacial chars, ie, Example@gmail.com' }, userId: { required: 'Alphanumeric, _, min:6, max:15', regex: "Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016" }, phoneNum: { required: "Please enter your phone number", regex: "e.g. +91-1234567890" }, }, submitHandler: function (form) { return true; } }); }
回答9:
we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.
therefore we use the following snippet
$.validator.addMethod( "regex", function(value, element, regstring) { // fast exit on empty optional if (this.optional(element)) { return true; } var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/); if (regParts) { // the parsed pattern had delimiters and modifiers. handle them. var regexp = new RegExp(regParts[1], regParts[2]); } else { // we got pattern string without delimiters var regexp = new RegExp(regstring); } return regexp.test(value); }, "Please check your input." );
Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).
You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use
$("#frm").validate({ rules: { Textbox: { pattern: /^[a-zA-Z'.\s]{1,40}$/ }, }, messages: { Textbox: { pattern: 'The Textbox string format is invalid' } } });
回答11:
This worked for me, being one of the validation rules: