How to apply two validations at the same time?

1

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

I wanted the two to be fired at the same time, what would be the most practical way to do this?

Here's 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><formid="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>
    
asked by anonymous 27.03.2018 / 14:34

2 answers

2

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

So the code gets 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><formid="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>
    
27.03.2018 / 14:55
0

You have to separate the click of the button, this happens because the javascript is asynchronous, it runs from top to bottom, so in your situation, it will execute test by test, that way it will fire both functions at the same time.

Your response will look like this:

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