I have a requirement in a username field where I have to validate the special characters but allow '.' dot character. We have custom method in plugin alphanumeric but it doesn't allow dot. please check the fiddle
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and . only please");
Use this regex /^[\w.]+$/i
You can use character set [] of regex to select multiple character.
^ in regex means it starts matching from the start of the string.
\w in regex means it accepts all alpha Numeric (A-Za-z0-9) and underscore (_).
I have added . inside the character set to allow character . also.
You can add more character inside the [] character set to allow them too.
+ in the regex means it will keep on matching all the character in the string.
$ in regex means it will check till the end of the line if its multi-line
i in regex is a flag that says its case insensitive.
Here is the updated fiddle
http://jsfiddle.net/YsAKx/330/
Updated JS
$(document).ready(function () {
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^[\w.]+$/i.test(value);
}, "Letters, numbers, and underscores only please");
$('#myform').validate({ // initialize the plugin
rules: {
field: {
required: true,
alphanumeric: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With