Orionis Orionis - 7 days ago 6
Javascript Question

HTML5 form validation without Javascript validation

I recently approached the new (for me) topic of HTML5 form validation. I tested it with success, but I'm still quite confused on how and why to use it.
Let me try to explain with a simple example.

My form have 10 fields (text, numbers, dates...); each one has it own

required
and
pattern
.

The
visual
validation works great; every fields shows the Go/NoGo status: this is fine.

But, when it comes to submit the form with javascript, should I have to re-validate each field?

In other words, the HTML5 validation is only a visual artifact; it does not prevent the form submission. If the user wants to input a wrong content disregarding the red flag, he can do it.

If I am correct with this, why should I use the HTML to do something that I can (and I must) do with JS?
Maybe there is way for JS to know the everything is Ok to proceed, without perform any further check.

Answer

When you apply an HTML validation via HTML to a form element and that element's value doesn't meet the validation criteria, the form will NOT be submitted.

But, if you get JavaScript involved, you will have to take control of this process. The simplest way is to simply check the form's validity.

"But, when it comes to submit the form with JavaScript, should I have to re-validate each field?"

As you'll see in my snippet, you will have to validate the form and this can be done with one simple method call. If needed, you can check each element to see which are invalid and why and act accordingly.

"In other words, the HTML5 validation is only a visual artifact; it does not prevent the form submission. If the user wants to input a wrong content disregarding the red flag, he can do it."

When you stick to just HTML and no JavaScript, then the validation is more than just visual. The form will not be submitted. That functionality is baked into HTML5 Form compliant browsers.

"If I am correct with this, why should I use the HTML to do something that I can (and I must) do with JS? Maybe there is way for JS to know the everything is Ok to proceed, without perform any further check."

Again, using just HTML markup will provide you with a variety of validators (required, pattern, number, etc.) and they will work, right out of the box. However, you won't get to control what the validation messages say or exactly when and where they will be displayed (or even how they look). That is all browser dependent. This is why the HTML5 Forms specification includes a very robust API (via JavaScript) counterpart - - for you to take complete control of the validation and notification process.

var btn = document.getElementById("btnSubmit");
var frm = document.getElementById("frmTest");


btn.addEventListener("click", function(){
  // The HTML 5 Forms API provides a .checkValidity()
  // method to your form object so that you can know
  // if the form is valid or not:
  if(frm.checkValidity()){
    frmTest.submit();
  }
});
<form method=post action="http://www.somewhere.com" id=frmTest>
  
  <input required>
  <input type=button id=btnSubmit value=submit>
  
</form>

Here is a basic JavaScript function that demonstrates what you can accomplish using the HTML5 Forms API:

  // Custom form validation logic:
  function validate(evt) {

    // An HTML5 form has a checkValidity() method which forces it
    // to examine the validity of all controls that know how to validate
    // and it returns a boolean indicating if ALL these controls are valid
    // or if any ONE of them is not.
    var valid = theForm.checkValidity();
    if (valid) {
      // Everything is good. Submit the form:
      theForm.submit();
    } else {
      // At least one form element is invalid. Loop through all the elements to
      // see which one(s) they are:
      var theElements = theForm.elements;

      for (var i = 0; i < theElements.length; i++) {
        var theElement = theElements[i];

        // If the form element participates in the HTML5 Validity Framework and
        // if it is invalid...
        if (theElement.willValidate && !theElement.validity.valid) {

          console.warn(theElement.id + " validity details: ");

          // ...The object will have a validity object property:
          console.log(theElement.validity);

          // The element is invalid. Loop through all the validity object's
          // properties to see why it is invalid:
          for (var constraint in theElement.validity) {

            // Check the particular validity constraint for true
            if (theElement.validity[constraint]) {
              // Update the span element next to the offending form element with the reason:
              theElement.nextElementSibling.innerHTML = constraint;
            }  // End If

          }  // End For

        }  // End If

      } // End For

    } // End If

  }  // End Function