check jquery email as if it were two strings

Asked

Viewed 204 times

2

Good evening, I’m finalizing a form check and I’ve locked on at one point, maybe by the way they wrote the code of my work I can’t use jquery validate, then I have trouble checking a field of input has a typed e-mail.

I made a validation code that counts the characters:

//verifica email
    $("#txtEmail").blur(function() {
        if ($("#txtEmail").val().length < 10) {
            $("#txtEmail").css('background', '#fb4745');
            $("#alertEmail").show('fast')
            $("#alertEmail").text('Preencha o campo com um email valido');  

        }
        if ($("#txtEmail").val().length >= 10) {
            $("#txtEmail").css('background', '#6ebe51'); 
            $("#alertEmail").hide('fast');
        } 
    });

My question is: can you make a code that detects if the email field is formed by a string + @ + string? Thank you for your attention!

2 answers

3


I usually use a regex like this [^@]+@[^@]+\.[^@]+. The idea is:

  • [^@]+ N characters other than @
  • once @
  • again N characters other than @
  • one time point (there may be more within [^@]+, but here requires there to be at least 1
  • again [^@]+

In your case it would look like this:

if ($("#txtEmail").val().match(/[^@]+@[^@]+\.[^@]+/)) {
   // etc...
}

Example:

var testes = [
  '[email protected]', 'falsomail(at)gmail.com'
];

testes.forEach(teste => {
  const match = teste.match(/[^@]+@[^@]+\.[^@]+/);
  console.log(teste, match ? 'válido' : 'inválido');
});

0

Maybe, <input type="email" .. /> also solve.

  • I tried, but probably the way they wrote the code was a mistake. So I found it easier to get around that than to search for the cause throughout the document and end up modifying something that depended on this "error in the code"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.