Do something by validating all input using event blur

0

is something basic I have never encountered this, I have several input that I'm validating through blur is when I lose the focus I review and do some action, the problem here is that I want to know when all my input are validated ... I have a structure like this;

const getId = id => document.getElementById(id);

  getId('primero')
    .addEventListener('blur', function(){
      if(this.value.length < 5){
        // fail
      }else{
        // valido
     }
   });

  getId('segundo')
    .addEventListener('blur', function(){
      if(this.value.length > 35){
        // fail
      }else{
        // valido
     }
   });

Now, how to know when my two input are valid and so I can do an action. Look for several examples but I am not really clear how to do it, I appreciate the help.

    
asked by Gabriela 26.10.2018 в 07:32
source

1 answer

0

Create a single function to validate all controls:

function validate() {
    if (getId('primero').value.length < 5) {
        console.log('validación incorrecta');
        return false;
    }
    if (getId('segundo').value.length > 35) {
        console.log('validación incorrecta');
        return false;
    }

    console.log('todo perfecto');
    // Aquí puedes añadir la acción que requieras
    return true;
}

Then you link that function in all affected controls:

getId('primero').addEventListener('blur', validate);
getId('segundo').addEventListener('blur', validate);
    
answered by 26.10.2018 в 08:57