HTML5 has a great degree of optimization for forms, whether it is semantics, widgets, or data format verification. I guess you will definitely use browser compatibility as an excuse not to use these "new features", but this should never be the reason for stagnation. Moreover, there are tool libraries like Modernizr and ployfill to help you when they are not supported. Perform fallback processing on Html5 browsers. When you actually try out these new form features, I guarantee you'll fall in love with it. If the only flaw is that the style of the prompt box is the default of the browser and you cannot change it, well, if you believe in the aesthetic level of the designers of the browser manufacturers (I believe their design level is better than that of most ordinary people) Better, if you don’t consider style compatibility), just learn it quickly!
Native validation
input type
HTML5 provides a lot of native support for data format validation, for example:
<input type='email'/>
When you click the submit button, if the format you enter does not match the email, it will not be submitted and the browser will prompt you with an error message.
For example, under chrome:
Note:
1. The browser verification will be triggered only when you submit
2. Different browsers The behavioral styles of the prompt information are different
3. When there are multiple inputs that do not meet the requirements, only an error will be prompted. Generally, the relatively earlier Input in the form will be prompted.
Do not take it for granted that when the input When the type is equal to tel, if the input you enter is not in the phone number format, it will be blocked by the browser and an error message will be prompted when submitting. Type='tel' only plays a semantic role on the PC side, but can be used on the mobile side. Making the generated keyboard a pure numeric keyboard does not play a role in data verification.
pattern
You can use the pattern attribute to set custom format validation for data formats that the browser does not provide native validation. The value of the pattern attribute is a regular expression (string):
<input type='tel' pattern='[0-9]{11}' title='请输入11位电话号码'>
When you click submit, if the data you enter does not conform to the regular format in pattern, the browser will prevent the form from being submitted, and Tip: 'Please keep it consistent with the requested format' + the content in the title (small print). But note that when the content in your text box is empty, the browser will not check it and will submit the form directly (because the browser thinks this box is not required). If you want this box to have content, add the required attribute.
Through the HTML native verification system, we can basically meet our restrictions on form submission. But HTML5 provides more advanced functions to facilitate our development and improve user experience.
Constraint Validation API
Default prompt message
Browser prompt message strings like 'Please be consistent with the requested format' are hidden in the input DOM In the validationMessage attribute of the object, this attribute is read-only in most modern browsers, that is, it cannot be modified. For example, the following code:
<input type="text" required id='input'/>
When submitted, if the Input content is empty, Then the browser will prompt 'Please fill in this field', and we can print this sentence on the console:
var input = document.getElementById('input') input.validationMessage // =>'请填写此字段'
If you want to modify the content, you can call the setCustomValidity interface to change the value of validationMessage
input.setCustomValidity('这个字段必须填上哦'); // 下面这种做法适用于不支持setCustomValidity的浏览器,基本现代浏览器都不支持这样做 input.validationMessage = '这个字段必须填上哦'
Note that although HTML native validation like required can change the information, it cannot set the information to an empty string, for reasons that will be discussed below.
Principle
The HTML form validation system uses the validationMessage attribute to detect whether the data in the text box has passed verification. If its value is an empty string, it means that the verification has passed, otherwise, it means that it has not passed. The browser will prompt the user with its value as an error message. Therefore, during native verification, users cannot set the value of validationMessage to an empty string.
A simple example of the constraint validation API
The constraint validation API is a more flexible expression on top of the native method. You can set whether the data passes by yourself without resorting to regular expressions. The principle is very simple. If you judge by if, if the data format satisfies you, then you call setCustomValidity to make the value of validationMessage empty. Otherwise, you call setCustomValidity to pass in the error message:
input.addEventListener('input', function () { if(this.value.length > 3){ // 判断条件完全自定义 input.setCustomValidity('格式不正确'); }else { input.setCustomValidity('') } });
Every time For keyboard input, the code will determine whether the format is correct, and then call setCustomValidity to set the value of validationMessage. Don't assume that the browser will prompt you whether the result is correct every time you press the button. The browser will only prompt you for the value in the validationMessage (if any) when you click the submit button.
If you haven't thought about it yet, you will definitely ask, in this case, why do you need to bind keyboard events to input and make a judgment every time you input? It is good to directly bind the submit event to the form, and then judge how good it is when submitting. Don't worry, it is beneficial to do so.
With the input judgment format and style
As a user, we certainly want the text box to turn red (or have other prompts) after knowing that I have entered the wrong format. And every time I enter a character, if it is correct, the text box returns to normal. We can use CSS pseudo-classes to achieve this function:
input:required { background-color: #FFE14D; } /*这个伪类通过validationMessage属性进行判断*/ input:invalid { border: 2px solid red; }
上面的required伪类会给所以必填但值空的input提供一个黄色的背景色,而下面的invalid伪类则会为所有未通过验证的input添加一个2px的红边边。我们现在给我们的Input框加上input类即可。
这些伪类的判断条件正与浏览器判断你能否提交表单的条件一样,看validationMessage里的值,所以,我们上面设置每次键盘输入事件都会触发一次判断从而改变CSS伪类样式的渲染,用意正在于此。
更好的用户体验
还有一个缺点,就是当一个input设置为required的时候,在初始化时,因为其本身是空的,所以invalid伪类会对它起作用,这不是我们想看到的,因为我们什么还都没有干。
我们可以并在这些伪类前加上父选择器.invalid,这样,只有在父元素具有invalid类时,这些伪类才会起作用。可以设置一个submit事件,在表单提交因验证失败后,会触发input的invalid事件,给form添加invalid类:
form.addEventListener('invalid', function() {this.className = 'invalid'}, true)因为invaild是Input的事件,而不是form的事件,所以这里我们设置第三个参数为true采用事件捕获的方式处理之。这样,就大功告成了。
最终实例
好了,现在是时候总结一下我们所学的知识并创造最佳实践了:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>form</title> <style> input:required{ background-color: #DCD4CE; } .invalid input:invalid{ border: 2px solid red; } </style> </head> <body> <form id="form"> <label>email:<input type="email" required id="email"></label> <label>IDCard:<input required id="IDCard"></label> <input type="submit" id="submit"> </form> <script> var email = document.getElementById('email'); var IDCard = document.getElementById('IDCard'); var form = document.getElementById('form'); IDCard.addEventListener('input', function () { if(this.value.length != 6) { this.setCustomValidity('IDCard的长度必须为6') }else{ this.setCustomValidity('') } }); form.addEventListener('invalid', function () { this.className = 'invalid'; }, true) </script> </body> </html>
运行后截图如下:
以上就是HTML5利用约束验证API来检查表单的输入数据的代码实例 的内容,更多相关内容请关注PHP中文网(www.php.cn)!