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 m
Have you tried this??
$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })
Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.
This worked for me, being one of the validation rules:
Zip: {
required: true,
regex: /^\d{5}(?:[-\s]\d{4})?$/
}
Hope it helps
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."
);
and
telephone: { required: true, regex : /^[\d\s]+$/, minlength: 5 },
tis better this way, no?
$.validator.methods.checkEmail = function( value, element ) {
return this.optional( element ) || /[a-z]+@[a-z]+\.[a-z]+/.test( value );
}
$("#myForm").validate({
rules: {
email: {
required: true,
checkEmail: true
}
},
messages: {
email: "incorrect email"
}
});
You can use the addMethod()
e.g
$.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.');
good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/
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'
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form id="frm" method="get" action="">
<fieldset>
<p>
<label for="fullname">Textbox</label>
<input id="Textbox" name="Textbox" type="text">
</p>
</fieldset>
</form>