Question: I am trying to validate email endings in an array
let input = '[email protected]' // This is grabbed dynamically but for sake of explanation this works the same
let validEndings = ['@gmail.com', '@mail.com', '@aol.com'] //and so on
if(input.endsWith(validEndings)){
console.log('valid')
}else{
console.log('invalid')
}
I can get this to work when validEndings is just a singular string e.g let validEndings = '@gmail.com'
but not when its in an array comparing multiple things
CodePudding user response:
You can solve the problem with regex. Example:
const input = '[email protected]';
const validEndingsRegex = /@gmail.com$|@mail.com$|@aol.com$/g;
const found = input.match(validEndingsRegex);
if (found !== null) {
console.log('valid')
} else {
console.log('invalid')
}
CodePudding user response:
You can check if the validEndings
is an array, then you can loop the values and find out if the input endsWith the current iterated item.
let input = '[email protected]' // This is grabbed dynamically but for sake of explanation this works the same
let validEndings = ['@gmail.com', '@mail.com', '@aol.com'] //and so on
if(Array.isArray(validEndings)) { // Check if validEndings isArray
validEndings.forEach(item => {
if(input.endsWith(item)){
console.log('valid item');
}
})
} else if(input.endsWith(validEndings)){ // If validEndings is normal string
console.log('valid')
}else{
console.log('invalid')
}