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.');
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…