0

I have used the following javascript code to add inline error in my form. I want to error to be removed after the error is corrected after each field is corrected. I have created a single function for all the validations, so not able to use else and remove the error manually.

var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/

var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}$/;

function validateForm() {
  var x = document.forms["LoginForm"]["email"];
  if (x.value == "") {
    x.value = "";
    document.getElementById('pointemail').innerHTML = "Please enter the email id.";
    x.focus();
    return false;
  } else if (!emailpattern.test(x.value)) {
    x.value = "";
    document.getElementById('pointemail').innerHTML = "Please enter a valid email address.";
    x.focus();
    return false;
  }
  x = document.forms["LoginForm"]["password"];
  if (x.value == "") {
    x.value = "";
    document.getElementById('pointpassword').innerHTML = "Please enter the password.";
    x.focus();
    return false;
  } else if (!passwordpattern.test(x.value)) {
    x.value = "";
    document.getElementById('pointpassword').innerHTML = "Password should have minimum 8 characters, one upper case, one lower case and one special character";
    x.focus();
    return false;
  }
}
1
  • Just add an else block at the end for valid state Commented Oct 17, 2016 at 6:48

2 Answers 2

1

Try This

var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/

var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}$/;

function validateForm() {
  var x = document.forms["LoginForm"]["email"];
  document.getElementById('pointemail').innerHTML = "";
  document.getElementById('pointpassword').innerHTML = "";

 //Add your if else here.
}

Hope it will be useful. :)

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

2 Comments

It will be useful if you dont want to use else. It will first blank and after that check.
you are running it by the change event?
0

Provide an extra else statement after elseif

else {
  document.getElementById('pointemail').innerHTML = '';
}

Similarly for pointPassword

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.