I am trying (and failing) to write a regular expression statement that checks for special characters such as !@#$%^&*()_+<>?\'\"{}[] in my Javascript form validation.
Few changes
jQuery.validator.addMethod("specialChars", function( value, element ) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = value;
if (!regex.test(key)) {
return false;
}
return true;
}, "please use only alphanumeric or alphabetic characters");
event.preventDefault()
, this has to be done in the keypress
event.Demo: Fiddle
Note: Since you are using +
wild char at least one character is required in the text box, you may want to split it into two rules using the required
rule and change the wild char to *
.
Instead of writing your own custom method from scratch, include the additional-methods.js file and use the alphanumeric
rule.
$(document).ready(function () {
$('#myform').validate({
rules: {
field: {
alphanumeric: true
}
}
});
});
Demo: http://jsfiddle.net/YsAKx/
If you don't want to include an additional external file, simply copy the default alphanumeric
method out of it...
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
^[a-zA-Z0-9;,.!@#$%:{}[]?"^&*()/\']*|[^&;<>\`]*
you want special charecter add here in this [] braces ^[a-zA-Z0-9;,.!@#$%:{}[]?"^&*()/\']
and you dont want then add here this part [^&;<>\
]`