I have the following code at JSfiddle:
http://jsfiddle.net/ACG2D/
$(document).ready(function() {
$('.testThis').click(function() {
$('.regexValidation').each(function() {
if ($(this).val() != "" || $(this).val() != null) {
// Check the regex
var expression = new RegExp('/^[0-9a-z_]+$/i');
var myVal = $(this).val();
if (expression.test(myVal) == true) {
// All is okay
alert("OK");
} else {
alert("Error");
}
}
});
});
});
The intended plan is to only let alphanumeric and underscores through. Disallowing spaces and punctuation etc.
I can't figure out why this is going wrong, but it always returns false for the test.
JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.
test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .
Definition and Usage. The test() method tests for a match in a string. This method returns true if it finds a match, otherwise it returns false.
match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.
Your syntax is wrong.
Change it to var expression = /^[0-9a-z_]+$/i;
Unlike PHP, Javascript supports regex literals the syntax /.../
creates a RegExp
object.
The RegExp
constructor takes a regex as a string, without separators.
Therefore, you could also write new RegExp('^[0-9a-z_]+$', 'i')
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