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.
Your syntax is wrong.
Change it to
var expression = /^[0-9a-z_]+$/i;Unlike PHP, Javascript supports regex literals the syntax
/.../creates aRegExpobject.The
RegExpconstructor takes a regex as a string, without separators.Therefore, you could also write
new RegExp('^[0-9a-z_]+$', 'i')