Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
Javascript onkeydown function not working properly

I wanted to check the entered email address properly with a Javascript function like this:

function validation() {
    let form = document.getElementById('form')
    let email = document.getElementById('email').value
    let text = document.getElementById('text')
    let pattern = "/^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/"

    if (email.match(pattern)) {
        form.classList.add('valid')
        form.classList.remove('invalid')
        text.innerHTML = "Valid"
        text.style.color = '#00ff00'
    } else {
        form.classList.remove('valid')
        form.classList.add('invalid')
        text.innerHTML = "Not valid"
        text.style.color = '#ff0000'
    }

    if (email == '') {
        form.classList.remove('valid')
        form.classList.remove('invalid')
        text.innerHTML = ""
        text.style.color = '#00ff00'
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
  <div class="form-group">
    <label for="email" class="col-sm-2 control-label">Email</label>
    <input type="email" name="email" class="form-control" id="email" placeholder="Enter your email" onkeydown="validation()">
    <span id="text"></span>
  </div>
</form>

Now it calls the validation() function properly and shows Not Valid message if user has entered an email address which is not validated.

But the problem comes from when the user tries to correct his email address and enters a valid email, but the message Not Valid still appears on page because of last incorrect email address.

So how can I properly hide this message when user enters valid email the 2nd time?

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

Try this code,

let pattern = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

// true if okay otherwise false.
pattern.test(email);

Thanks.

about 4 years ago · Santiago Gelvez Denunciar

0

If you are looking for standard email validation, then message not valid still appears because it is not valid according to your pattern. See more email regular patterns in different questions.

function validation() {
    let email = document.getElementById('email').value
    let yourPattern = "/^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/"
    let anotherPattern = /\S+@\S+\.\S+/;
    
    console.log("is yourPattern valid?", !!email.match(yourPattern));
    console.log("is anotherPattern valid?", !!email.match(anotherPattern));

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
    <input type="email" name="email" class="form-control" id="email" placeholder="Enter your email" onkeydown="validation()">
</form>

about 4 years ago · Santiago Gelvez Denunciar

0

Maybe use HTML5's <input type="email" required> for the validation. If you need to do any further tests in JS you can, but this is a nicer way of doing it, and you get built-in messages.

A further note on validation however.

const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);

function handleSubmit(e) {
  e.preventDefault();
  const data = new FormData(form);
  console.log(data.get('email'));
}
input[type="email"]:not(:placeholder-shown):invalid { border-color: red; }
<form>
  <input name="email" placeholder="Add an email" type="email" required>
  <button type="submit">Submit</button>
</form>

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda