.match() with a regular expression returns null

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.');
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)