html - HTML5 form validation without Javascript validation - Stack Overflow

I recently approached the new (for me) topic of HTML5 form validation. I tested it with success, but I&

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 es 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.

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 es 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.

Share Improve this question edited Dec 1, 2016 at 15:44 Casper S 9541 gold badge13 silver badges31 bronze badges asked Dec 1, 2016 at 15:25 OrionisOrionis 1,0211 gold badge8 silver badges14 bronze badges 2
  • Similar question – Mosh Feu 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. – Alexander Taran Commented Dec 1, 2016 at 15:51
Add a ment  | 

6 Answers 6

Reset to default 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.

<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>

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 es 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 pliant 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 plete 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." id=frmTest>
  
  <input required>
  <input type=button id=btnSubmit value=submit>
  
</form>

Here is a basic JavaScript function that demonstrates what you can acplish 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

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.

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

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 pared 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742332345a4423968.html

相关推荐

  • html - HTML5 form validation without Javascript validation - Stack Overflow

    I recently approached the new (for me) topic of HTML5 form validation. I tested it with success, but I&

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信