I have function like this:
var name_regex = /^[a-zA-Z0-9_ -]{3,32}$/,
body_regex = /^[a-zA-Z0-9_ -]$/,
email_regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,
phone_regex = /^[0-9-]{3,32}$/,
error_count;
function validation_test (name, value) {
var test_name = name + '_regex';
console.log(test_name);
error_count = 0;
if(!test_name.test(value)){
error_count += 1;
}
}
And if I try to run it (on submit) I get following error:
test_name.test is not a function
console.log(test_name) is giving me the proper name for the variable (for example name_regex). How can I make this variable work?
4 Answers 4
Just use an object:
var regexes = {
name: /^[a-zA-Z0-9_ -]{3,32}$/,
body: /^[a-zA-Z0-9_ -]$/,
email: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,
phone: /^[0-9-]{3,32}$/
};
function isValid(name, value) {
return regexes[name].test(value);
}
In your other code:
if( !isValid( "phone", 123 ) ) {
alert("Invalid phone");
}
9 Comments
window[test_name] if he wants to.error_count to 0 every time validation_test is called, is that intentional?error_count is useless then. You might as well return true or false because you are not keeping any count, the result is always either 0 or 1 which is better expressed by false and trueAre you trying to call the function e.g.
validation_test('phone', '9184079201');
If so, I'd recommend putting your regular expressions into an object:
var regex = {
'name': '...',
'body': '...',
'email': '...',
'phone': '...',
};
function validation_test(name, value) {
if(!regex[name].test(value)) {
//...
}
}
That way you can look them up by string.
1 Comment
variable test_name should be proper regExp object https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test
consider
...
function validation_test (name, value) {
var test_name = name + '_regex';
console.log(typeof(test_name)); // string
...
Than happen because of concatenation on the line above console log
2 Comments
test_name is a string, not the regex it represents, so !test_name.test(value) won't do what you want.
Since you're not using name anywhere else in the function, why don't you just pass the regex in as an argument?
function validation_test (test_name, value) {
error_count = 0;
if(!test_name.test(value)){
error_count += 1;
}
}
test_namecontains the name of a function you want to run?window[test_name]if it is defined in the global scope. Elsenamespace[test_name]wherenamespaceis the namespace where the variable to test are defined in.testis one of the methods of regular expression object, not the string.