0

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";
  }
2
  • 2
    It did not "jump over", the later if statements overwrite the same value if multiple conditions are true. You need to use else if instead of if for the consecutive conditions. Commented Feb 21, 2019 at 2:00
  • Got it! Thanks a lot! Commented Feb 21, 2019 at 3:53

2 Answers 2

2

It does execute in order, but then your second if is simply overwriting the message from the first if. You need to add code to end processing if the first if is true, or use else iffor the second.

Sign up to request clarification or add additional context in comments.

Comments

0

Look at the 2 snippets, and look at the difference. If you just use if (true), every single one will execute. To make only one execute, use if else ().

if (true) {
  console.log("First statement is true!");
}
if (true) {
  console.log("Second statement is true!");
}
if (true) {
  console.log("Third statement is true!");
}

if (true) {
  console.log("First statement is true!");
}
else if (true) {
  console.log("Second statement is true!");
}
else if (true) {
  console.log("Third statement is true!");
}

In your case, it both executed, but since the second one executed after the first one, errors.name had the value from the second if but not the first.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.