Validate multiple emails with JavaScript - javascript

I have 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;
} else {
return true;
}
}
}
The problem is that when I test the email like this if(!self.validateEmails(multipleEmails)) { i get true or false based only on the first email in the string, but I want to test for any email in the string.
Thank you!

The problem is your if/else block; You are returning under both conditions. Which means that it leaves the function after evaluating only one element.
I've modified validateEmails to demonstrate what you probably want to do:
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;
}

how about this?
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
var errors = [];
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
errors[i] = result[i] + ' is not valid.';
}
}
if (errors.length > 0) {
alert(errors.join('\n'));
return false;
} else {
return true;
}
}

in case you use jquery-validate the validation method would look like:
jQuery.validator.addMethod("separated_emails", function(value, element) {
if (this.optional(element)) {
return true;
}
var mails = value.split(/,|;/);
for(var i = 0; i < mails.length; i++) {
// taken from the jquery validation internals
if (!/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(mails[i])) {
return false;
}
}
return true;
}, "Please specify a email address or a comma separated list of addresses");

I find the most maintainable way is to use a variable to store the return output.
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(/,|;/);
var allOk = true;
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
allOk = false;
}
}
return allOk;
}

This code below is perfect to validate multiple email addresses separated with comma or semicolon using JQuery:
var emailReg = new RegExp(/^([A-Z0-9.%+-]+##[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+##[A-Z0-9.-]+.[A-Z]{2,6}))*$/i);
var emailText = $('#email').val();
if (!emailReg.test(emailText)) {
alert('Wrong Email Address\Addresses format! Please reEnter correct format');
return false;
}

Related

Do I have a problem with my javascript or is it something else?

(I would like to adress that English is not my first language)
I have this problem with javascript for a very long time and I don't know what to do.
This javascript is for a registration. Sometimes it gives access even though I haven't typed everything, or it doesn't give access even though I have typed everything correctly
If someone can help thanks already!
function validateform() {
var res = true;
res = userNameVal() && res;
res = passowrdVal() && res;
res = ConfirmPhone() && res;
res = emailConfirm() && res;
res = Name() && res;
res = lastName() && res;
res = city() && res;
return res;
}
function Name() {
var firstName = document.getElementById("firstName").value;
var msgBox = document.getElementById("NameMsg");
if (firstName.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (reg.test(firstName) && reg1.test(firstName) && reg2.test(firstName) && (English(firstName))) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function lastName() {
var LastName = document.getElementById("LastName").value;
var msgBox = document.getElementById("LastNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (Name.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
if (reg.test(LastName) || reg1.test(LastName) || reg2.test(LastName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function city() {
var CityName = document.getElementById("CityName").value;
var msgBox = document.getElementById("CityNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (CityName.length == 0) {
msgBox.innerHTML = "You must enter your City";
return false;
}
if (reg.test(CityName) || reg1.test(CityName) || reg2.test(CityName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function userNameVal() {
var userName = document.getElementById("userName").value;
var msgBox = document.getElementById("userNameMsg");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter a username";
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "Your username must start with a letter";
return false;
}
msgBox.innerHTML = "";
return true;
}
function passowrdVal() {
var pass = document.getElementById("password").value;
var msgBox = document.getElementById("passwordMsg");
var specialChar = /[#!#$%^&*()-+]/;
if (pass.length == 0) {
msgBox = "You must enter a password";
return false;
}
if (pass.length < 7) {
msgBox.innerHTML = "The password must contain at least 7 charactes"
return false;
}
if (!specialChar.test(pass)) {
msgBox.innerHTML = "password must contain one special letter ";
return false;
}
msgBox.innerHTML = "";
return true;
}
function ConfirmPhone() {
var phone = document.getElementById("phone").value;
var msgBox = document.getElementById("phoneMsg");
var reg = /^0{1}(2|3|4|6|8|9|5[0|[2-8]|73)-?[1-9]\d{6}$/;
if (!reg.test(phone)) {
msgBox.innerHTML = "Phone number is illegal";
return false;
}
msgBox.innerHTML = "";
return true;
}
function emailConfirm() {
var email = document.getElementById("email").value;
var msgBox = document.getElementById("emailMsg");
var reg = /^\w+/;
if (!reg.text(email)) {
msgBox.innerHTML = "Mail can hava only one following letter";
return false;
}
msgBox.innerHTML = "";
reg = /^\w+([\.-]?\w+)*#\w+/;
if (!reg.test(email)) {
msgBox.innerHTML = "Mail must have #";
return false;
}
reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!reg.test(email)) {
msgBox.innerHTML = "invalid email";
return false;
}
msgBox.innerHTML = "";
return true;
}
function isLetter(ch) {
if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"))
return true;
return false;
}
function isDigit(ch) {
if (ch >= "0" && ch <= "9")
true;
false;
}
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
We need more information about exactly what happens in your success and failure cases. However I see potential issues here:
For me, this function does not work for two reasons:
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
First, the variable i is not declared, do you mean this:
let i = 0
Possibly, i is declared globally, and so you are inadvertently trashing another value? Generally using let is preferable to using var, you can have other unexpected effects on globals if you use var.
Second, I don't see how this is working. For me str[i].isLetter is not defined.
while (str[i].isLetter) {
Do you intend to use your isLetter() function
isLetter(str[i])
If that doesn't help you will need to explain in more detail what happens in your failure cases.

I am getting confused about how do i write a switch case instead of the if condition using javaScript only

here is my validation function which I wanted to define using the switch case but I'm confused about how to fit this particular code in the switch case.
function validation() {
var formrdvalid = false;
var fname = document.getElementById("fname").value;
var city = document.getElementById("city");
var radios = document.getElementsByName("gender");
var agree = document.getElementById("invalidCheck").checked;
if (fname == "") {
alert("please enter firstname");
}
if (city.selectedIndex === 0) {
alert("select the city");
return false;
}
if (!formrdvalid) {
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
formrdvalid = true;
}
}
}
if (!formrdvalid) {
alert( "please select gender");
return false;
}
if(agree === false){
alert("agree terms and conditions");
}
if (!fname||!city || !radios || !agree ) {
return false;
} else {
return true;
}
}
I think it's possible. And sometimes (maybe not in your case) it's really useful.
To do so, you should declare a variable that represent whole state of form, like this:
var formrdvalid = false;
var fname = document.getElementById("fname").value;
var city = document.getElementById("city");
var radios = document.getElementsByName("gender");
var agree = document.getElementById("invalidCheck").checked;
// this represents state of the form, including all important info
// like a table
var state = `${formrdvalid}|${fname}|${city}|${radios}|${agree}`;
// now you should just list all valid states
switch(state) {
case `true|myform|London|22|true`:
case VALID_STATE2:
case VALID_STATE3:
return true;
default:
return false;
}
Sometimes it is more convenient to define invalid cases and return true by default.

regex test alwayes returns false

$("#pincode").blur(function () {
var pincode = $("#pincode").val().trim();
var pattern = /^[0-9]{6}$/;
if (pincode != "" && !IsPatternFormate(pincode, pattern)) {
$("#pincode").addClass('invalidValidation');
document.getElementById('pincode')
.setCustomValidity('please enter data in proper formate');
}
});
var IsPatternFormate = function (value, pattern) {
var match = pattern.test($(value));
console.log(match);
}
i don't know why, match always return me false value.
var IsPatternFormate = function (value, pattern) {
if(pattern.test(value)){
return true;
}else{
false;
}
}
Change your IsPatternFormate function

Javascript: Check if all elements of an array are the same as a variable, or none of them are

I have a javascript variable that is an array of arrays. Then I have a variable below it. Like this:
var cars = [
["ford mustang",1955,"red"],
["dodge dart",1963,"green"],
["pontiac",2002,"green"],
]
var colour = "blue";
Now I need to check for if either the third values of each array are all the same as the variable, colour, or they are all different. If one of those conditions are true, I want to execute some other code. So in the above example, the condition would be true because none of the values are "blue". It would also be true if they were all "blue".
Hopefully I've made myself clear.
There are two functions in JavaScript just for that:
allCarsAreRed = cars.every(function(car) { return car[2] == 'red' })
atLeastOneCarIsRed = cars.some(function(car) { return car[2] == 'red' })
noRedCars = cars.every(function(car) { return car[2] != 'red' })
some
every
var colour = 'blue'
var all = true;
var none = true;
for (var i = 0; i < cars.length; i++) {
if (cars[i][2] !== colour) {
all = false;
} else {
none = false;
}
}
Do you need something like this?
var cars_length = cars.length;
var all_same = true;
var all_different = true;
for(var i=0; i<cars_length; i++)
{
if(cars[i].[2] == colour)
{
all_same = false;
}
else
{
all_different = false;
}
}
if(all_same)
{
console.log('all same');
}
else
{
if(all_different)
{
console.log('all different');
}
else
{
console.log('nor all same, nor all different');
}
}
Look at bellow Solution
var arr = ["a", "b", "c", "d"]
var allZero = true;
for (var i = 0; i < arr.length; i++)
{
if (arr[i][2] != 0)
{
allZero = false;
break;
}
}
if (allZero)
{
console.log("ALL are Zero");
}

javascript: how to remove last entry?

Suppose i have the following JS code, i can only remove the whole characters whenever it receives non-acceptable character(s):
function checkInput() {
document.getElementById("message").setAttribute('maxlength', (456));
for (var i = 0; i < document.fr_upload.message.value.length; i++) {
if (!checkLatin(document.fr_upload.message.value)) {
alert("Your entry does not contain latin type.\n Please try again.")
document.fr_upload.message.value = '';
document.fr_upload.char_left.value = 0;
return false;
}
}
}
function checkLatin(arg) {
var latin = /^[\u0020-\u007E]*$/;
if (arg.match(latin)) {
return true;
} else {
return false;
}
}
Thus, how can i remove only non-acceptable character?
Try
function checkInput() {
document.getElementById("message").setAttribute('maxlength', (456));
var value = document.fr_upload.message.value;
if (value && !/[^\u0020-\u007E]/.test(value)) {
alert("Your entry contains non latin characters.\n Please try again.");
document.fr_upload.message.value = value.replace(
/[^\u0020-\u007E]/g, '');
document.fr_upload.char_left.value = document.fr_upload.message.value.length;
}
}
To replace the non-latin characters you can use:
function removeNonLatin(arg) {
var nonlatin = /!(^[\u0020-\u007E]*$)/g;
arg = arg.replace(nonlatin , '');
return arg;
}

Categories