I am trying to do something I thought would be pretty easy to do, which is to restrict a string to certain characters by matching a regular expression.
var v
Regex must be surrounded with /
, not '
, so that JavaScript creates a variable of type regex, not of type string. So for instance, for your ALPHA case, you should have
regex = /^[a-zA-Z]+$/;
See MDN's page on .match for more information about using .match
.
Your code looks like it's inside a function { ... }
. Are you return
ing anything? If not, that's why you're getting null
back...
Also, regexes are surrounded by slashes (/.../
), not quotes.
You want RegExp.test
, which tests a value for a match instead of retrieving the match. With your existing code, that would mean:
if(!new RegExp(regex).test(value)){
alert('Your string was invalid.');
}
However, it would be preferable to use RegExp literals instead of strings, as they're much more efficient and clear, and less prone to error:
var value = 'FailureStr1ng';
var type = 'ALPHA';
var regex = null;
switch(type) {
case 'ALPHA':
regex = /^[a-zA-Z]+$/;
break;
case 'NUMERIC':
regex = /^[0-9]+$/;
break;
case 'ALPHANUMERIC':
regex = /^[a-zA-Z0-9]+$/;
break;
}
if(!regex.test(value)) {
alert('Your string was invalid.');
}
Even better, use a dictionary:
var expressions = {
ALPHA: /^[a-zA-Z]+$/,
NUMERIC: /^[0-9]+$/,
ALPHANUMERIC: /^[a-zA-Z0-9]+$/
};
if(!expressions[type].test(value)) {
alert('Your string was invalid.');
}