Multiple Email Validation using regex. Loop terminates after first validation - javascript

I think I am very close here.
I'm trying to iterate through an array and at each iteration, check whether the value is a valid email address.
The problem is, the loop terminates once it hits either a false or a true. How do I iterate through an array without terminating the loop?
validateForm: function() {
var emails = $('#email-addresses').val(),
emailArray = emails.split(',');
for (var i = 0; i < emailArray.length; i++) {
if( ! this.validateEmail(emailArray[i].trim())) {
return false;
}
return true;
};
},
validateEmail: function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}

It depends on what you want to do here. If you want to hold a result for every check then look at lincb answer. If you want just a true / false about whether all emails were valid then do:
validateForm: function() {
var emails = $('#email-addresses').val(),
emailArray = emails.split(',');
var isValid = true;
for (var i = 0; i < emailArray.length && isValid == true; i++) {
if( ! this.validateEmail(emailArray[i].trim())) {
isValid = false;
}
};
return isValid;
},

In Javascript, return will end the function regardless of any loops. Here is a possible fix:
validateForm: function() {
var emails = $('#email-addresses').val(),
emailArray = emails.split(',');
var returns = new Array();
for (var i = 0; i < emailArray.length; i++) {
if( ! this.validateEmail(emailArray[i].trim())) {
returns[i] = false;
}
returns[i] = true;
}
return returns;
},

Related

Breaking from a recursive function and returning a value in Javascript

I have written a javascript function like this . But I want when a cretain condition meet the function will not execute means it will break and return a true false like status.My code is like this
var ActionAttributes = function (data)
{
var status = true;
var attrKey = data.AttributeKey();
//Condition to exit
if (attrKey==''||attrKey==null)
{
status = false;
return false;
}
for (var i = 0; i < data.Children().length; i++)
{
var childData = data.Children()[i];
ActionAttributes(childData);
}
return status;
}
You need break condition in the for loop. You are just invoking it, handle the returned status.
var ActionAttributes = function(data) {
var status = true;
var attrKey = data.AttributeKey();
//Condition to exit
if (attrKey == '' || attrKey == null) {
status = false;
return false;
}
for (var i = 0; i < data.Children().length; i++) {
var childData = data.Children()[i];
//You need to break loop here
//Add appropriate condition here
if (ActionAttributes(childData) == false) {
return false;
}
}
return status;
}
well, that recursion is not very useful to begin with.
you call a recursion of ActionAttributes inside the loop, but never handle the returned status. So the first caller will always receive true unless the exit condition meets on the first object.
you shoul store the return from ActionAttributes into status, and then break out of the loop as soon as it's false.

Execute the else statement if none of the items are found

I have this for loop, and I would like to execute the else in the for loop only if none of the if conditions are met. The for loop runs until every item in the database has been checked. If none of the items in the database matches the user input then I want to run the else.
Right now, it runs the else right after the first try which means if the item matches is in the last row, it will just throw it in the error page since it stops the evaluation at the first iteration.
for(var i=0; i< rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
}
else {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
}
Just move the else portion outside of the loop and execute it based on a flag
var wasFound = false;
for (var i = 0; i < rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// ...
wasFound = true; // set the flag here
}
}
if (!wasFound) {
res.render('invalidHashtag', {});
}
So add a check outside.
var hasMatch = false;
for (var i = 0; i < rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
hasMatch = true;
}
}
if (!hasMatch) {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
Create a variable to track whether your condition has been met:
var isValid = true;
for(var i=0; i< rows.length; i++) {
if (rows[i].hashtag != userEnteredHashtag) {
isValid = false
}
}
isValid ? res.render('chooseBox') : res.render('invalidHashtag')
Another way to do it is to use filter and forEach.
var rows = [{hashtag: '#a'}, {hashtag: 'b'}, {hashtag: 'c'}];
var userEnteredHashTag = '#a';
var matchingRows = rows.filter(row => row.hashtag === userEnteredHashTag);
if (matchingRows.length) {
matchingRows.forEach(row => console.log(row));
} else {
console.log('invalid');
}

How to display the string content of this array all at once using javascript?

I am using this for form validation. I call this function when there is an error and i send it a string as a parameter.
var errList = new Array();
function aerrorList(error){
errList.push(error);
for (var i=0; i < errList.length; i++){
alert(errList[i]);
}
}
here is one of the validation checks:
function lNameValidate() {
var lName = document.getElementById("lastname");
if (lName.value.length < 20 && /^[a-zA-Z0-9- ]*$/.test(lName.value)){
stNumValidate();
} else {
lName.style.border = "red";
errorList("Invalid lName Format");
stNumValidate();
}
}
The current array (using alert) displays the error in a number of popup boxes with only 1 error string each. i want it to display 1 alert which would show all the errors in a list similar to outputting it in a bullet point way.
You can append all the errors to one var and then display it:
function aerrorList(error){
errList.push(error);
var errors = "";
for (var i=0; i < errList.length; i++){
errors += errList[i] + "\n";
}
alert(errors);
}
You could use join method on an array, Here's an example:
errors=['error1','error2','error3']
Here, a is an array of list of your errors, now you can glue them together using whatever you want like this:
error_string=error.join("\n*")
Finally you can make an alert:
alert(error_string)
Try this:
var Errors = {
messages: [],
push: function(message) {
this.messages.push(message);
},
alert: function() {
alert(this.messages.join("\n"));
},
showInElement: function(element) {
element.innerHTML = this.messages.join('<br/>');
},
clear: function() {
this.messages = [];
}
}
var age = 1;
if(age < 18) {
Errors.push("Come back when You 18+");
}
var name = "Jack";
if(name != "John") {
Errors.push("You're not John!");
}
Errors.alert();
var element = document.getElementById('content');
Errors.showInElement(element);
Errors.clear();
<div id="content"></div>
So I ended up using this:
var errList = new Array();
function errorList(error){
errList.push(error);
}
function showErrors() {
alert(errList.join("\n"));
}
where i just call showErrors on the very last validation check if the errList length is > 1 as such:
function emailRestrict() {
var eVal = document.getElementById("email").value;
var atPos = eVal.indexOf("#");
var dotPos = eVal.lastIndexOf(".");
if (atPos < 1 || dotPos < atPos || dotPos >= eVal.length) {
errorList("not valid email");
if (errList.length > 1){
showErrors();
}
return false;
}
else {
if (errList.length > 1){
showErrors();
}
return true;
}
}

jQuery: Validate Multiple Emails

So I found these two functions:
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
return false;
}
}
return true;
}
from this question:
Validate multiple emails with JavaScript
Can anyone tell me what does the variable "shareEmail" mean ? It is not defined and I don't understand what it means, what is it's purpose?
I have a feeling the code you didn't show looks like this:
showEmail = {
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
},
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
return false;
}
}
return true;
}
};
In which case shareEmail's value is self-evident.

Why am I getting an empty alert box?

I have js function onsubmit forms
var bCancel = false;
var errors = new Array();
function validateNewsForm(form) {
if (bCancel) {
return true;
} else {
errors = [];
var statusArray = new Array();
statusArray.push(validateRequired(form));
statusArray.push(validateMaxLength(form));
statusArray.push(validateDate(form));
for (status in statusArray) {
if (!status) {
alert(errors.join('\n'));
return false;
}
}
return true;
}
}
validateSmth() functions work fine. But when I input correct data I can't save because get empty alert. I have just one alert message and now that all validate functions gives true( in case correct data)
Why can I get empty alert?
for (status in statusArray) {
if (!status) {
A for in loop gives you keys. For an array these are indices. So you're effectively doing !0, !1, etc, and !0 evaluates to true.
You want a normal for loop:
for(var i = 0; i < statusArray.length; i++) {
if (!statusArray[i]) {
Also, you're using [] and new Array() together. It's best to just use [] everywhere.
because for status = 0 !status will be true.
Modified code:
for (var status = 0; status < statusArray.length; status ++) {
if (!statusArray[status] ) {
alert(errors.join('\n'));
return false;
}
}

Categories

Resources