How to apply two validations at the same time?

Asked

Viewed 63 times

1

I am trying to create a simple validation of two fields, where I only check whether there is a value or not, but the second if only runs after the first one is checked.

I wanted the two of them to be shot at the same time, which would be the most practical way to do it?

Follow the example of my current validation:

    $(document).ready(function(){

$('#formLogin').on('submit', function(e){
    if($('#txtLogin').val() == ''){
        e.preventDefault();
        if (!$('.err-text').length) {
            $('#txtLogin').closest('.login__column').append(`<span class="err-text">*E-mail incorrecto.
<br>Ingresa un E-mail válido para participar.</span>`);
        }
    } else {
        $('#txtLogin').next('.err-text').remove();
    }
    if($('#txtSenha').val() == ''){
        e.preventDefault();
        if (!$('.err-text').length) {
            $('#txtSenha').closest('.login__column').append(`<span class="err-text">*Contraseña incorrecta.
<br>Ingresa una contraseña válida para participar.</span>`);
        }
    } else {
        $('#txtSenha').next('.err-text').remove();
    }
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formLogin">
<div class="login__column">
<input type="text" id="txtLogin">
</div>
<div class="login__column">
<input type="text" id="txtSenha">
</div>
<button type="submit">Enviar</button>
</form>

2 answers

2


I put a each in your code, so it will go through the two inputs and place error messages at the same time.

This makes code more dynamic and easier to maintain.

$(document).ready(function() {
  $('#formLogin').on('submit', function(e) {
    e.preventDefault();
 
    $(this).find('input[type=text]').each(function() {
      if($(this).val() == '') {
        if (!$(this).next('.err-text').length) {
            var texto = $(this).attr('id') == 'txtLogin' ? '*E-mail incorreto' : '*Senha incorreta';
            $(this).parent().append('<span class="err-text">' + texto +'</span>');
        }
      } else {
        $(this).next('.err-text').remove();
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formLogin">
<div class="login__column">
<input type="text" id="txtLogin">
</div>
<div class="login__column">
<input type="text" id="txtSenha">
</div>
<button type="submit">Enviar</button>
</form>

0

You have to separate the click from the button, this happens because javascript is asynchronous, running from top to bottom, so in your situation, will perform test by test, so it will trigger both functions at the same time.

Your answer will stay that way:

$('#formLogin').on('submit', function(e){
    //teste
}
$('#formLogin').on('submit', function(e){
    //segundo teste
}

Browser other questions tagged

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