简体   繁体   English

没有Javascript验证的HTML5表单验证

[英]HTML5 form validation without Javascript validation

I recently approached the new (for me) topic of HTML5 form validation. 我最近接触了HTML5表单验证的新主题(对我来说)。 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...); 我的表格有10个字段(文字,数字,日期......); each one has it own required and pattern . 每个人都有自己的requiredpattern
The visual validation works great; visual验证效果很好; every fields shows the Go/NoGo status: this is fine. 每个字段都显示Go / NoGo状态:这很好。
But, when it comes to submit the form with javascript, should I have to re-validate each field? 但是,当提交使用javascript的表单时,我是否应该重新验证每个字段?
In other words, the HTML5 validation is only a visual artifact; 换句话说,HTML5验证只是一个视觉工件; 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? 如果我对此是正确的,为什么我应该使用HTML来做我能做(而且我必须)用JS做的事情? Maybe there is way for JS to know the everything is Ok to proceed, without perform any further check. 也许JS有办法知道一切都没问题继续进行,没有进行任何进一步的检查。

In other words, the HTML5 validation is only a visual artifact; 换句话说,HTML5验证只是一个视觉工件; 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. 根据设计,HTML5验证防止提交错误填写的表单。 And it does — in most browsers . 它确实 - 在大多数浏览器中 Unfortunately, there is a bug in Safari that leads to the behavior you described. 不幸的是, Safari中存在一个导致您描述的行为的错误 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. 因此,如果修复了这个错误,是的,您可能也需要使用JS验证表单,但这不是因为HTML5验证的性质,只是因为它缺乏对Safari的支持。

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. 当您通过HTML将HTML验证应用于表单元素并且该元素的值不符合验证条件时,将不会提交表单。

But, if you get JavaScript involved, you will have to take control of this process. 但是,如果您涉及JavaScript,则必须控制此过程。 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?" “但是,当提交使用JavaScript的表单时,我是否应该重新验证每个字段?”

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." “换句话说,HTML5验证只是一个视觉工件;它不会阻止表单提交。如果用户想要输入错误的内容而忽略红旗,他就可以做到。”

When you stick to just HTML and no JavaScript, then the validation is more than just visual. 当您坚持使用HTML而不使用JavaScript时,验证不仅仅是可视化的。 The form will not be submitted. 表格将不会提交。 That functionality is baked into HTML5 Form compliant browsers. 该功能已融入HTML5 Form兼容的浏览器中。

"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." “如果我对此是正确的,为什么我应该使用HTML来做我可以(并且我必须)使用JS做的事情?也许JS有办法知道一切都可以继续,而不进行任何进一步的检查。 “

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. 同样,仅使用HTML标记将为您提供各种验证器(必需,模式,数字等),它们将开箱即用。 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. 这就是为什么HTML5 Forms规范包含一个非常强大的API(通过JavaScript)对应 - 为您完全控制验证和通知过程。

 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: 这是一个基本的JavaScript函数,演示了使用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验证未通过时,浏览器不应让用户提交表单。 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. HTML5提供了良好的验证,但如果您想要更复杂的验证,或者如果您想要针对不支持HTML5验证的浏览器,则使用js。

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

您可以阻止提交时的默认行为(包括html5的表单验证),并通过js开始此验证来处理数据。

Here is an example where you can validate a input field asking for a name using HTML5 form validation: 下面是一个示例,您可以使用HTML5表单验证验证要求输入名称的输入字段:

<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. 使用pattern属性时,隐含正则表达式的开头和结尾的^和$,不需要包含它们。

You can help the user by including a title attribute that tells them the format you require. 您可以通过包含一个title属性来帮助用户,该属性告诉他们您需要的格式。

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: 要确保用户在电子邮件,网站和票证数字段中输入正确的数据,您可以使用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. 通过指定适当的类型,您的浏览器将为您验证数据,并确保您在电子邮件字段中有一个电子邮件地址,网站字段中有一个URL,以及票数字段中的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM