user13465472
user13465472

Reputation: 117

How to set condition for onclick validation javascript

I am facing one small problem to set the message and clear the message.

I have 2 input where onclick of the button I should check the input fields satisfies the condition else don't show any message

OR

if error message was displaying after condition gets satisfied I should remove the message

but the code below doesn't satisfies if phnum is 10 digit and pincode is less than 7 digit and vise versa

if both field length doesn't satisfy on click of button i should display both the error messages

const inputValidation = () => {
  if (phnum?.length < 10) {
    //phnum must be 10 digit(error message)
    if (picode?.length < 7) {
      //zipcode must be 7 digit (error message)
    } else {
      //remove  zipcode message
    } else {
      //remove phnum message
    }
  }
}

Upvotes: 0

Views: 46

Answers (1)

mplungjan
mplungjan

Reputation: 177940

  1. Move the clear errors before the ifs
  2. Move the second if since now you only test picode if phnum is in error
const inputValidation = () => {
  //remove  zipcode message
  //remove phnum message
  if (phnum?.length < 10) {
    //phnum must be 10 digit(error message)
  } 
  if (picode?.length < 7) { // removing the else will show both
    //zipcode must be 7 digit (error message)
  }
}

Upvotes: 2

Related Questions