mercredi 20 février 2019

Execution order of consecutive if statements in javascript

I have a couple of if statements for validation purpose.

The problem now is that the order of validating is not as what I expected.

For example, I want to check if the name field if empty, and if it is empty, check if it is between 2 and 30 characters. But when I test it, if I leave the name filed blank, it gives me the error "Name must be between 2 and 30 characters" first. It seems it jumped over the first if statement.

So, why this is the case? Why it doesn't execute in order

  if (Validator.isEmpty(data.name)) {
    errors.name = "Name field is required";
  }

if (!Validator.isLength(data.name, { min: 2, max: 30 })) {
    errors.name = "Name must be between 2 and 30 characters";
  }



 if (Validator.isEmpty(data.email)) {
    errors.email = "Email field is required";
  }

  if (!Validator.isEmail(data.email)) {
    errors.email = "Email is invalid";
  }

Aucun commentaire:

Enregistrer un commentaire