Reputation: 1086
I have the following code at JSfiddle:
$(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.
Upvotes: 7
Views: 14233
Reputation: 881
use slash "/" instead of quotes, at the beginning and end of the regular expression.
for your code, it should be like this -
var expression = new RegExp(/^[0-9a-z_]+$/i);
Upvotes: 0
Reputation: 888223
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')
Upvotes: 13
Reputation: 16470
Remove quotes from your RegExp:
var expression = new RegExp(/^[0-9a-z_]+$/i);
Upvotes: 10