JQuery Method Validation Validation for Special Characters
I'm trying (and failing) to write a regex instruction that checks for special characters like! @ # $% ^ & * () _ + <>? '"{} [] in my Javascript form validation.
I realize this has probably been asked 1000 times, but I'm under some serious pressure. If you prefer not to answer the question below, and you can point me towards the previous answer to the above question, I would really appreciate it.
On a similar note, can anyone tell me why the following happens on error when I enter lowercase "abc", etc.? I am puzzled.
jQuery.validator.addMethod("specialChars", function( value, element ) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}, "please use only alphanumeric or alphabetic characters");
source to share
Instead of writing your own method from scratch, include the file additional-methods.js
and use the rule alphanumeric
.
$(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, just copy the alphanumeric
default method from it ...
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
source to share
Several 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");
- You need to return true if the test is valid.
- The validator is not an event handler, so you cannot use it
event.preventDefault()
, it must be done in an eventkeypress
. - You need to check the value passed to the check method.
Demo: Fiddle
Note. Since you are using +
wild char, at least one character is required in the text field, you can split it into two rules with a rule required
and change wild char to *
.
source to share