I have following regular expression in JQuery. It always returns true.
var reg = new RegExp("[a-zA-Z0-9 ,]+");
var key = $('#keyId').val().trim();
if (key.match(reg)) {
$("#TitleError").hide();
}
else {
$("#TitleError").text("special characters not allowed!!").show();
}
It returns true for everything, for example "ABCD, ^&&&^&" should be false, it returns true.
JavaScript RegExp test()If it finds a match, it returns true, otherwise it returns false.
Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string. It returns an array of information or null on a mismatch. Tests for a match in a string.
But to elaborate, re. match() will return either None , which evaluates to False , or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
match
returns the matches found in the string. what you really want is test
eg. like this
/^[a-zA-Z0-9 ,]+$/.test(key)
or
reg.test(key)
You regexp should be:
var reg = new RegExp('^[a-zA-Z0-9 ,]+$');
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