I have 5 functions that check user input against regular expressions…these regular expressions have been abstracted out and put here as suggested in previous post.
Now I want to abstract out the functionality and put the code into an associative array per the previous post as well..however their seemed to be some contention as to whether this is best practice? Is this O.K to do?
Is it good practice to put these functions into an associative array of functions? The previous post doing this is not up..as I’m guessing they decided against it.
But basically how to do you group similar methods together properly.
EDIT 1: // consolidated regular expressions
var patterns = {
name: /^[a-zA-Z-\s]{1,20}$/,
email: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/,
pass: /.{6,40}/,
url: /^[-\w&:\/\.=\?,#+]{1,}$/,
aml: /<(.+)_([a-z]){1}>$/
};
// checks full name which allows characters and dashes
function check_name(text,id,res)
{
for(var d=0;d<=0;d++)
{
if(!patterns["name"].exec(text.value))
{
o2(id,res);
return 0;
}
}
return 1;
}
// checks for valid email form
function check_email(text,id,res)
{
if(!patterns["email"].exec(text.value))
{
o2(id,res);
return 0;
}
return 1;
}
// checks for password length
function check_pass(text,id,res)
{
if(!patterns["pass"];.exec(text.value))
{
o2(id,res);
return 0;
}
return 1;
}
// checks for valid url form
function check_url(text,id,res)
{
if(!patterns["url"].exec(text.value))
{
o2(id,res);
return 0;
}
return 1;
}
// checks for aml form
function check_aml(text)
{
if(a=patterns["aml"].exec(text))
{
if(a[2]=='p')
{
return 0;
}
else if (a[2]=='f')
{
return 1;
}
}
else
{
return 2;
}
}
I don’t think there are any issues with creating a common place to store your patterns. This in fact seems like a good approach. However I don’t see the need to have your individual checking functions be made aware of the global storage. They should instead be made simply aware of the pattern they are checking and the source against which they check. If you take this approach your checking code can be dramatically simplified
Here I’ve removed the notion of the global storage from the checking function. Since the rest of the code is so similar it can be abstracted out to a single method which is passed the pattern it’s looking to match.