Estoy usando indexOf para ver si un correo electrónico contiene algo más que un texto en particular.
Por ejemplo, quiero verificar si un correo electrónico NO incluye "usa" después del símbolo @ y mostrar un mensaje de error.
Primero estaba dividiendo el texto y eliminando todo antes del símbolo @:
var validateemailaddress = regcriteria.email.split('@').pop();Luego, compruebo si el texto no incluye "usa":
if(validateemailaddress.indexOf('usa')){ $('#emailError').show(); }Algo con la comprobación anterior no parece correcto. Funciona: puedo ingresar un correo electrónico y, si no incluye 'usa', aparecerá el mensaje de error.
De todos modos, cuando agrego una verificación adicional, como si el correo electrónico no incluye "puede", el mensaje de error aparece sin importar qué.
Como sigue:
if(validateemailaddress.indexOf('usa') || validateemailaddress.indexOf('can')){ $('#emailError').show(); }Como se indicó, al usar lo anterior, el mensaje de error se mostrará independientemente de si el correo electrónico incluye el texto o no.
Todo lo que quiero hacer es verificar si el correo electrónico incluye 'usa' o 'can', y si no es así, mostrar el mensaje de error.
¿Cómo puedo hacer que esto funcione?
Aquí hay una función de JavaScript simple para verificar si una dirección de correo electrónico contiene 'usa' o 'can'.
function emailValid(email, words) { // Get the position of @ [indexOfAt = 3] let indexOfAt = email.indexOf('@'); // Get the string after @ [strAfterAt = domain.usa] let strAfterAt = email.substring(indexOfAt + 1); for (let index in words) { // Check if the string contains one of the words from words array if (strAfterAt.includes(words[index])) { return true; } } // If the email does not contain any word of the words array // it is an invalid email return false; } let words = ['usa', 'can']; if (!emailValid('abc@domain.usa', words)) { console.log("Invalid Email!"); // Here you can show the error message } else { console.log("Valid Email!"); }Hay varias formas de verificar si una cadena contiene/no contiene una subcadena.
Cadena.prototipo.incluye
'String'.includes(searchString); // returns true/falseCadena.prototipo.indexOf
// returns values from -1 to last postion of string. 'String'.indexOf(searchString); // In combination with ~ this can work similar to includes() // for strings up to 2^31-1 byte length // returns 0 if string is not found and -pos if found. ~'String'.indexOf(searchString);Con la ayuda de expresiones regulares:
// substring must be escaped to return valid results new RegExp(escapedSearchString).test('String'); // returns true/false if the search string is found 'String'.match(escapedSearchString); // returns null or an array if foundEntonces, en general, puede usar casi todos los métodos como:
if ('String'.function(searchString)) { // 'String' includes search String } else { // 'String' does not include search String }O en el caso de indexOf:
if ('String'.indexOf(searchString) > -1) { // 'String' includes search String } else { // 'String' does not include search String } // OR if (~'String'.indexOf(searchString)) { // 'String' includes search String } else { // 'String' does not include search String }Puedes hacer algo así, usando include:
const validateEmailAdress = (email) => { const splittedEmail = email.split('@').pop(); return (splittedEmail.includes('usa') || splittedEmail.includes('can')) } console.log("Includes usa: ", validateEmailAdress("something@gmail.usa")) console.log("Includes can: ", validateEmailAdress("something@gmail.can")) console.log("Does not includes: ", validateEmailAdress("something@gmail.com"))