How to allow validation for multiple email addresses using javascript - javascript

I am using javascript to validate my page, I have done the validation for email which should follow the basic rules of email id. But I need the validation to allow multiple email addresses. Can anyone please help in adding this. Thanks in advance.
Here is JS Code:
function function1(){
var exp = /^(([^<>()[\]\\.,;:\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,}))$/;
var emailid = document.getElementById('mailid').value;
if(emailid == '' || emailid == null){
document.getElementById('error4').innerHTML = "* Enter Email ID";
document.getElementById('mailid').focus();
return false;
}else{
document.getElementById('error4').innerHTML = "";
}
if (!exp.test(emailid)) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
}

You could do something like this:
var emails = emailid.split(",");
emails.forEach(function (email) {
if(!exp.test(email.trim()) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
});

You should split your emailid string into an array and then check the emails one by one
var emails = emailid.split(',');
You can know more about the split method here http://www.w3schools.com/jsref/jsref_split.asp

Assuming the addresses are separated by comma you could do something like this:
(untested but you should get the idea)
var theString = "an.address#domain.ext, an.other.address",
stringProper = theString.replace(/\s/g,''),
addresses = stringProper.split(','), //creates an array of every email
allValid = true;
for (var i = addresses.length - 1; i >= 0; i--) {
if (addresses[i] == 'an.other.address') {
isValid = true;
} else {
isValid = false;
}
if(!isValid) {
allValid = false;
break;
}
};
function isEmail (theString) {
var exp = /^(([^<>()[\]\\.,;:\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 exp.test(theString)
}

Related

Why is my Javascript form validation not working properly?

Why is my validation failing on second attempt here? On first attempt the validation works fine, but on the second run, it will accept inappropriate values in the email field. The first two fields work fine, but the third field will accept any text after the first run. However it only validates if I change the value in the email field, otherwise it will keep displaying the error and failing to validate like it should.
function validate(){
clearErrors();
var errorFlag = true;
var name = document.getElementById("name");
nameVal = name.value;
if(nameVal.length === 0){
var nameError = document.getElementById("nameError");
nameError.style.display = "block";
errorFlag = false;
}
var phone = document.getElementById("phone")
var phoneVal = phone.value;
if(isNaN(phoneVal) || (phoneVal < 1000000000 || phoneVal >10000000000)){
errorFlag = false;
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "block";
}
var email = document.getElementById("email");
var emailVal = email.value;
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
errorFlag = false;
var emailError = document.getElementById("emailError");
emailError.style.display = "block";
}
return errorFlag;
}
function clearErrors(){
var nameError = document.getElementById("nameError");
nameError.style.display = "none";
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "none";
var emailError = document.getElementById("emailError");
emailError.style.display = "none";
}
Your validator will fail on the email, because you are feeding a string to .match, when it needs a regex.
You also have to call .match on the email itself, with the regex as the argument.
You also need to negate the return value to check if it does not match, or use .test.
This bit:
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
Should be replaced with:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!emailVal.match(re)){
Of if you can't use a regex literal for some reason:
var re = new RegExp("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$", "i");
if(!emailVal.match(re)){
Or using .test instead of .match:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!re.test(emailVal)){
Note the i for case-insensitive matching, so emails don't have to be entered in all-caps.

How to make a simple webpage register form using cookies? (jQuery)

I'm making a register/login form in javascript. User should enter information about himself and the computer should put that information into an array and remember it but it 'forgets' it every time I reload the page.
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
...more code
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
Any ideas to solve this? I have one more question. How can I check weather is an username alerady in use?
Here is the full js code:
var main = function() {
var people = [];
var cookies = [];
$('#register_email').val("");
$('#register_username').val("");
$('#register_password').val("");
$('#register2_password').val("");
function Person(username, email, password, repeat_password) {
this.username = username;
this.email = email;
this.password = password;
this.repeat_password = repeat_password;
}
$('#register').click(function() {
var username = $('#register_username').val();
var email = $('#register_email').val();
var password = $('#register_password').val();
var r_password = $('#register2_password').val();
if( email==="" || username==="" || password==="" || r_password==="") {
$('#error').text("You didn't fill everything");
}
else {
people[people.length] = new Person(username, email, password, r_password);
for(var key in people) {
//This should check weather this username was used before but I'm not really sure what to insert instead of "name"
if(people[people.length - 1].username === "name") {
$('#error').text("This username is already in use");
break;
}
else if(password !== r_password) {
$('#error').text("Passwords don't match");
break;
}
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
}
}
});
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
};
$(document).ready(main);
There is a js-fiddle live example in comments.

Convert multiple alerts to one alert

I'm using javascipt to validate a form and the code is like below,
function validateForm() {
console.log("start check form");
var errors = [];
var form = document.getElementsByTagName('form')[0];
/*
* Store appropriate form elements.
* There are many ways to do this, but I'm keeping it
* simple for the example
*/
var fnElem = document.getElementById("name");
var lnElem = document.getElementById("phone");
var firstName = fnElem.value;
var lastName = lnElem.value;
// etc...
// validate required fields
if (firstName === "") {
errors.push({
elem: firstName,
message: "name can't be blank"
});
}
if (lastName === "") {
errors.push({
elem: lastName,
message: "phone can't be blank"
});
}
for(var i=0; i<errors.length;i++){
alert(errors[i].message);
}
return false;
}
and in the for loop it will alert lots of times in the windows.
how can I combine all the alert into one single message..and only alert once.
I know that I can define a string and append one by one, But that seems so fool.
Is there a better way to do this.
First you map the error array to the contained messages: array.map().
Then you can join the messages: array.join().
if (errors.length) {
alert("Errors:\n" + errors.map(function (e) { return e.message; }).join('\n'));
}
Change your loop to append the message to a variable, then alert after the loop:
var messages = "";
for(var i=0; i<errors.length;i++){
messages += errors[i].message + "\n";
}
alert(messages)
for( var sAlert = '', i = 0, iL = errors.length; i < iL; ++i ) {
sAlert += errors[i].message + '\n';
}
alert(sAlert );
I didn't had a closer look at your code but if everything is fine this should solve it :)

how to compare the value

This my code
I am getting email address from database through ajax and mysql it is giving me value in . so in below FUNCTION comparing() i am retriving data from span to compare with the textfield data. but it is not comparing properly.
Please help me out
function validate(pageForm)
{
/************Getting error values in return values***********************/
var returncomparing = "";
/*********************************/
//FIELD WHICH YOU HAVE TO VALDATE
returncomparing += comparing(pageForm.email);
/********************************************/
if (returncomparing != "")
{
document.getElementById('error').innerHTML = returnIndustry;
}
return false;
}
After giving correct EMAIL still it is giving Error ... (Please Provide Login User ID)
function comparing(pageForm){
var error = "";
// var fetchedEmail=document.forms["pageForm"]["email_fetch"].value;
var em=document.forms["pageForm"]["email"].value;
//var emai = document.getElementById('emlTst').value;
var email = document.getElementById('txtHint').innerHTML;
//document.getElementById('emlTst').value = email;
if(em != email){
document.getElementById('error_email2').innerHTML="Please Provide Login User ID";
pageForm.style.borderColor = 'red';
error='5';
}
else if(em == email){
document.getElementById('error_email2').innerHTML="";
error = "";
}
else {
document.getElementById('error_email2').innerHTML="";
pageForm.style.borderColor = '#c7c7c7';
}
return error;
}
/*************************************************************/
var em = $('#email').val().toLowerCase();
var email = $('#txtHint').val().toLowerCase();

Creating a login in javascript - array comparison

I have a login box using a simple javascript login comparing usernames and passwords, before you all start I know about the security issues in using javascript for authentication. Here is the code
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters", "Jonathan Goss", "Lisa Cain", "Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
document.getElementById("mandatory1").value = un;
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
At the moment if the login is successful I'm posting the username to a hidden field which is then being used by a piece of a software. How do I associate the names in fnArray with the other correct username & password so that I can then grab associated full name and post that to the hidden field "mandator1" instead?
You can get the index of the correct user
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters, Jonathan Goss, Lisa Cain, Jenny Dempsey"];
var index = 0;
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
index = i;
break;
}
}
now you can access the correct data using
unArray[index];
// and so on for other arrays
Define a variable for full name, and set it if you have the valid user:
var fn = "";
/* ... */
valid = true;
fn = fnArray[i];
/* ... */
document.getElementById("mandatory1").value = fn;
Note: Actually you can check validity later on using fn. If it is empty string, then no user was logged in. This makes it have same purpose as valid, and more.
Try this.
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = -1;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters","Jonathan Goss","Lisa Cain","Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = i;
break;
}
}
if (valid != -1) {
alert ("Login was successful");
document.getElementById("mandatory1").value = fnArray[valid];
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
set mandatory1 when the login is successful based on i (in the for loop)

Categories

Resources