Reputation: 632
I'm doing a function to validate emails adresses, an user can enter several emails, separated by semicolon. I want to try my function with different cases, so I made a jsfiddle. But when i Try to run the fiddle, it seems it crashes when calling my function IsValidEmailFormat.
this is the function I want to test.
function IsValidEmailFormat(input) {
var isValid = true;
if (input.length > 0) {
var emailsToValidate = input.split(";");
//this regex for the common mail format
var regExp1 = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
for (i = 0; i < emailsToValidate.length-1; i++) {
if (!regExp1.test(emailsToValidate[i])) {
isValid = false;
return isValid;
}
//TODO: Add more validations rules if neccesary
}
}
return isValid;
}
Any idea? Here's my fiddle
Upvotes: 1
Views: 458
Reputation: 42053
The problem is in the for
loops, you need to define i
to be a local variable otherwise you will have issues with scoping and your loops won't work as expected.
Change these
for (i = 0; i < testEmails.length-1; i++) {
for (i = 0; i < emailsToValidate.length-1; i++) {
to
for (var i = 0; i < testEmails.length-1; i++) {
for (var i = 0; i < emailsToValidate.length-1; i++) {
Upvotes: 2
Reputation: 2103
You need to user var
. What I think was happening is when you don't use var the variable becomes global and it was messing up your for loops. The for loop in runTests
doesn't ever finish because you keep resetting i
back to 0
or 1
(The max size of any testEmails
array)
You also needed to escape things in your regular expression. I changed it to a regular expression literal so it would be easier to spot.
So my fiddle should be working.
function runTests() {
var div = $("#testResults");
var line;
for (var i = 0; i < testEmails.length; i++) {
console.log(testEmails[i]);
line = "<p>" + testEmails[i] + "</p>";
result= IsValidEmailFormat((testEmails[i]));
console.log(result);
div.append(line);
}
}
function IsValidEmailFormat(input) {
var isValid = true;
if (input.length > 0) {
var emailsToValidate = input.split(";");
//this regex for the common mail format
var regExp1 = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
for (var i = 0; i < emailsToValidate.length; i++) {
console.log("testing", i);
if (!regExp1.test(emailsToValidate[i])) {
isValid = false;//
return isValid;
}
//TODO: Add more validation example
}
}
return isValid;
}
Upvotes: 1