How can I configure my own regular expressions for validation in the jqueryvalidation plugin?
I don't understand anything from the documentation. It seems that this possibility should logically be just in
$('form').validation({
rule(
);
});
1
Author: Raz Galstyan, 2017-06-09
3 answers
This plugin does not have a standard validation method that allows you to specify your own regular expressions, but you can add it yourself:
$.validator.addMethod('regexp', function(value, element, params) {
var expression = new RegExp(params);
return this.optional(element) || expression.test(value);
});
And use it like this:
$('form').validate({
rules: {
name: {
regexp: /^[a-z]+$/
}
}
});
2
Author: Maxim Zasorin, 2017-06-09 22:24:07
jQuery.validator.addMethod( name, method [, message ] )
Example: add a validation method that checks whether a string starts with a specific domain name.
jQuery.validator.addMethod("domain", function(value, element) {
return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
}, "Please specify the correct domain for your documents");
Description: An object containing all the validation methods known to the validator. Can be used to override individual methods, keeping messages as default.
Example. Sets a custom template email address for the built-in email verification rule.
$.validator.methods.email = function( value, element ) {
return this.optional( element ) || /[a-z]+@[a-z]+\.[a-z]+/.test( value );
}
$('form').validation({
rules: {
email: {
required: true,
email: true
}
}
});
1
Author: Alex78191, 2017-06-09 22:30:49
Add it additional-methods.js
or pattern.js
and the jQuery Validation plugin will use the HTML5 attribute pattern
.
<input type="text" name="somename" pattern="[A-Za-z0-9\w]{4,20}" />
$(document).ready(function() {
$('#myform').validate({
debug: true
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.js"></script>
<form id="myform">
<input type="text" name="fullname" pattern="[A-Za-z0-9\w]{4,20}" required="required" />
<input type="submit" />
</form>
1
Author: Alex78191, 2017-06-09 22:43:35