3

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.

2
  • Similar question Commented Dec 1, 2016 at 15:29
  • There is nothing "you must do". There are different opportunities to solve a task at hand. Having validation attributes at her disposal one can avoid using javascript for simple form validation. Sometimes it is ok. Sometimes you are better of with javascript. Commented Dec 1, 2016 at 15:51

6 Answers 6

2

In other words, the HTML5 validation is only a visual artifact; it does not prevent the form submission.

It's not how it is supposed to work. By design, HTML5 validation should prevent the incorrectly filled form from submission. And it does — in most browsers. Unfortunately, there is a bug in Safari that leads to the behavior you described. So until this bug if fixed, yes, you might need to validate the form with JS, too, but it's not because of the nature of HTML5 validation, only because of the lack of its support in Safari.

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

Comments

2
<form method="GET" action="Your Action Page" id="contact form">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" placeholder="name" id="name" class="form-control" required="true" pattern="[a-zA-z]+">
</div>

<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="email" placeholder="email" class="form-control" required="true" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
</div>

<div class="form-group">
<label>Mobile No:</label>
<input type="tel" name="number" id="number" placeholder="Phone No"pattern="^\d{10}$" required="true" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onkeydown="if(this.value.length==10 &amp;&amp; event.keyCode!=8 &amp;&amp; event.charCode != 9 &amp;&amp; event.which != 9 ) return false">
</div>

<div class="submit-area">
<input type="submit" id="submit-contact" name="submit" class="btn-alt" value="Send Message">
<div id="msg" class="message"></div>
</div>
</form>

2 Comments

edit your answer and add some explanation how this code solves the issue
Basic HTML5 Form Validation for Beginners
0

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

14 Comments

@Alexander Taran Please don't edit someone's answer so that it is saying something fundamentally different than the author wrote.
Instead of a click handler, you should really be handling the form submit. There are alternative ways of submitting a form, such as simply pushing enter on an input field.
@Brad You'll note that the button is not a submit button, so a click event is the correct approach. If you are going to submit via JavaScript, you shouldn't use a submit button because you will then have to potentially cancel the event and bubbling.
Who is downvoting all these answers? Both this one and mine seem to be valid answers.
I bet you don't use it and it's just for the code preview, but anyway you probably should consider not using "// End For" etc. Correct tab indents are enough, like this you can teach someone bad code habit.
|
0

When HTML5 validation do not pass, the browser should not let user to submit the form. HTML5 offers good validation, but if you want more sophisticated validating, or if you want to target on browsers that don't support HTML5 validation, then use js.

3 Comments

HTML5 provides a very robust validation API.
@Scott Marcus ok, I know, fixed, I just wanted to point out that for more complex validation he should use js.
Your wording makes is sound like using JavaScript means that you are no longer using HTML5 and that's not true. HTML5 isn't just markup - it includes many JavaScript APIs.
-1

You can prevent default behaviour on submit (including form validation of html5) and start this validation by js to process the data.

Comments

-1

Here is an example where you can validate a input field asking for a name using HTML5 form validation:

<input id="name" name="name" value="" aria-describedby="name-format" required aria-required=”true” pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname">

You'll want the 'Name' field to be submitted in the format 'Firstname Lastname', and to only contain letters and a space. You can achieve this by adding a pattern attribute to the 'Name' field, setting it's value to the regular expression we want the data to be compared against.

When using the pattern attribute, the ^ and $ for the start and end of the regular expression are implied and don't need to be included.

You can help the user by including a title attribute that tells them the format you require.

To make sure your user enters the right data in the email, website, and number of tickets fields, you can use some of the new input types added in HTML5:

<input type="email" id="email" name="email" required>
…
<input type="url" id="url" name="url">
…
<input type="number" id="numTickets" name="numTickets" required>

By specifying the appropriate type, your browser will validate the data for you and make sure you've got an email address in the email field, a URL in the website field, and a number in the number of tickets field.

2 Comments

@Scott Marcus I found your answer very useful and I do not understand the down-voting (I voted it). I believe that the 'frm.checkValidity()' is what I was looking for. Possibly I did not explain clearly my doubts, due to my English too. I'm not 'posting' the form in the usual way; contents are gathered by JS, elaborated and later send to a PHP mailer. For this reason, I leave to HTML to perform the validation and only when everything is ok JS takes control of the second phase. Your solution seems perfect
Ok, I'm glad you found it useful. I sometimes feel that this game of upvoting and downvoting answers in stackoverflow is extremely childish! It turns everyone against each other.

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.