Reputation: 125
I am making a function to validate form input data (for practice) and maybe i'll also use it.
I was wondering if there is some way to apply the same functionality without eval as i have heard that it is bad on the js interpreter. Also improvements, if any. And also i would like to know if there is something that does the same job, ie, to apply reusable regex rules to input fields.
Here is my JavaScript validation function.
function validate(){
var num=/[0-9]+/g;
var alphanum=/[0-9a-zA-Z_]+/g;
var alphanumSpace=/[0-9a-zA-Z\w_]+/g;
var alpha=/[a-zA-Z]+/g;
var alphaSpace=/[a-zA-Z\w]+/g;
var alphanumDot=/[0-9a-zA-Z\._]+/g;
var money=/[0-9]+\.?[0-9]{0,2}?/g;
var flag=true;
var alertBox="Incorrect entries:\n\n";
$.each($('input[data-check]'),function(index,value){
if(!eval(value.dataset.check+'.test("'+value.value+'")')){
alertBox+=value.name+",\n";
flag=false;
}
});
alert(alertBox);
return flag;
}
Which is used to call on a form as
<form onsubmit="return validate()">
On fields that have the data-check attribute as any of the matching variables that i have defined as
<input data-check='num'>
This will call the test the regex against the num regex as defined in my code.
Upvotes: 0
Views: 297
Reputation: 36703
You can do something like this using new RegExp
and window[]
:
$.each($('input[data-check]'),function(index,value){
var str = value.value;
var patt = new RegExp(window[value.dataset.check]);
var res = patt.test(str);
if(!res){
alertBox+=value.name+",\n";
flag=false;
}
});
Upvotes: 1