Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Email address validation using jquery

I am working on email validation for a login page using jQuery. The problem I am facing is only the else part is getting executed and not if part. Below is the code.

$(document).ready(function () {
    $('#my-input').focusout(function () {
        emailValidate();
    });

    function emailValidate() {
        var reg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
        var email = $('#my-input').val();
        if (reg.test('email')) {
            console.log('correct');
            $('#my-input').css('border', '2px solid green');
            $('#span1').css('display', 'none');
        } else {
            $('#my-input').css('border', '2px solid red');
            $('#span1').css('display', 'block');
        }
    }
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Should be email as Variable, not as String

var email = $('#my-input').val();
if ( reg.test(email) ) {

Here's a slight remake with the mentioned fix.
It uses a CSS class to determine the styles. JS is only used to toggle that has-error class from the common parent label element.

It also doesn't uses IDs. data-validate is a far more flexible option!

const has = {
  value: (val) => val.trim().length > 0,
  email: (val) => /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(val),
  // add more validators here
};


jQuery(function($) { // DOM ready and $ alias inn scope

  function validate() {
    const isValid = has[this.dataset.validate](this.value);
    $(this).closest("label").toggleClass("has-error", !isValid);
  }

  $("[data-validate]").on("focusout", validate);
  
});
/*QuickReset*/ *,*::before,*::after{margin:0; box-sizing:border-box;}
body {font:16px/1.6 sans-serif;}


label {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  margin: 5px;
  border: 2px solid transparent;
}

label input {
  flex: 1;
}

label.has-error {
  border: 2px solid red;
  border-image-slice: 1;
  border-image-source: linear-gradient(to right, red, fuchsia);
}

label .error {
  color: red;
  display: none;
}

label.has-error .error {
  display: inline-block;
}
<label>
  <span class="placeholder">Name:</span>
  <input type="text" name="name" data-validate="value">
  <span class="error">Name cannot be empty</span>
</label>
<label>
  <span class="placeholder">Email:</span>
  <input type="text" name="email" data-validate="email">
  <span class="error">Invalid Email address</span>
</label>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

PS: makes no sense to use "green" colors to mark something OK in UI. It's the same logic in which you would never show an alert box saying "Hey! Your email is correct!". Users presume it's correct if not marked otherwise.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda