Skip to content Skip to sidebar Skip to footer

How Do I Validate This Html/javascript Form Onsubmit?

I have managed to figure out how to 'error' alert if the passwords do not match, but this does not prevent a user from still submitting the form altogether. Can someone please expl

Solution 1:

The easiest way to prevent the default behavior of the form submit is to have your function return false. This will stop the form from submitting.

var onSubmitHandler = function(event){
    /* validate here */returnfalse;
};

The other (and technically better) way is to call preventDefault on the event object that is passed as a parameter to your onSubmit function. The only issue is that some older versions of IE don't support this method, so you'll need to provide a fallback for this case:

var onSubmitHandler = function(event){
    /* validate here */if(event.preventDefault)
        event.preventDefault();
    elseevent.returnValue = false;
};

Solution 2:

Use the cool, new-ish Constraint Validation API:

constsetPasswordValidity = () => {
    const valid = pass2.value === pass1.value;

    for (let el of [pass1, pass2]) {
        if (valid) el.setCustomValidity("");
        else el.setCustomValidity("Passwords do not match!");
    }
};

pass1.onchange = setPasswordValidity;
pass2.onchange = setPasswordValidity;
setPasswordValidity();

It's well supported these days.

Solution 3:

Historically, I have used the following idea:

functionvalidateForm() {
  var errors = 0;
  var form = document.getElementsByTagName('form')[0];

  /* 
   * Store appropriate form elements.
   * There are many ways to do this, but I'm keeping it 
   * simple for the example
   */var firstName = document.getElementById("firstName").value;
  var lastName = document.getelementById("lastName").value;
  // etc..// validate required fieldsif (firstName === "") {
    errors++;
  }

  if (lastName === "") {
    errors++;
  }

  // etc...return errors === 0;
}

You can also make the errors more robust...

functionvalidateForm() {
  var errors = [];
  var form = document.getElementsByTagName('form')[0];

  /* 
   * Store appropriate form elements.
   * There are many ways to do this, but I'm keeping it 
   * simple for the example
   */var fnElem = document.getElementById("firstName");
  var lnElem = document.getelementById("lastName");
  var firstName = fnElem.value;
  var lastName = lnElem.value;
  // etc...// validate required fieldsif (firstName === "") {
    errors.push({
      elem: firstName,
      message: "First name can't be blank"
    });
  }

  if (lastName === "") {
    errors.push({
      elem: lastName,
      message: "Last name can't be blanks"
    });
  }

  // etc...return errors.length === 0;
}

You could then loop through the errors and do something useful.

Post a Comment for "How Do I Validate This Html/javascript Form Onsubmit?"