check email in jquery as if it were two string

2

Good evening, I'm finalizing a form check and I caught it at one point, maybe because of the way they wrote my work code I can not use jquery validate , so I have trouble verifying that a input field has an e -mail typed.

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!

    
asked by anonymous 17.04.2017 / 01:08

2 answers

3

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

  • [^@]+ N characters other than @
  • once @
  • again N characters other than @
  • at one point (there may be more within [^@]+ , but here you must have 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');
});
    
17.04.2017 / 01:13
0

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

    
18.04.2017 / 01:05