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='請(qǐng)輸入11位電話號(hào)碼'>
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 // =>'請(qǐng)?zhí)顚懘俗侄?amp;#39;
If you want to modify the content, you can call the setCustomValidity interface to change the value of validationMessage
input.setCustomValidity('這個(gè)字段必須填上哦');
// 下面這種做法適用于不支持setCustomValidity的瀏覽器,基本現(xiàn)代瀏覽器都不支持這樣做
input.validationMessage = '這個(gè)字段必須填上哦'
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;
}
/*這個(gè)偽類通過(guò)validationMessage屬性進(jìn)行判斷*/
input:invalid {
border: 2px solid red;
}
上面的required偽類會(huì)給所以必填但值空的input提供一個(gè)黃色的背景色,而下面的invalid偽類則會(huì)為所有未通過(guò)驗(yàn)證的input添加一個(gè)2px的紅邊邊。我們現(xiàn)在給我們的Input框加上input類即可。
這些偽類的判斷條件正與瀏覽器判斷你能否提交表單的條件一樣,看validationMessage里的值,所以,我們上面設(shè)置每次鍵盤輸入事件都會(huì)觸發(fā)一次判斷從而改變CSS偽類樣式的渲染,用意正在于此。
更好的用戶體驗(yàn)
還有一個(gè)缺點(diǎn),就是當(dāng)一個(gè)input設(shè)置為required的時(shí)候,在初始化時(shí),因?yàn)槠浔旧硎强盏模詉nvalid偽類會(huì)對(duì)它起作用,這不是我們想看到的,因?yàn)槲覀兪裁催€都沒(méi)有干。
我們可以并在這些偽類前加上父選擇器.invalid,這樣,只有在父元素具有invalid類時(shí),這些偽類才會(huì)起作用。可以設(shè)置一個(gè)submit事件,在表單提交因驗(yàn)證失敗后,會(huì)觸發(fā)input的invalid事件,給form添加invalid類:
form.addEventListener('invalid', function() {this.className = 'invalid'}, true)因?yàn)閕nvaild是Input的事件,而不是form的事件,所以這里我們?cè)O(shè)置第三個(gè)參數(shù)為true采用事件捕獲的方式處理之。這樣,就大功告成了。
最終實(shí)例
好了,現(xiàn)在是時(shí)候總結(jié)一下我們所學(xué)的知識(shí)并創(chuàng)造最佳實(shí)踐了:
<!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的長(zhǎng)度必須為6')
}else{
this.setCustomValidity('')
}
});
form.addEventListener('invalid', function () {
this.className = 'invalid';
}, true)
</script>
</body>
</html>
運(yùn)行后截圖如下:

以上就是HTML5利用約束驗(yàn)證API來(lái)檢查表單的輸入數(shù)據(jù)的代碼實(shí)例?的內(nèi)容,更多相關(guān)內(nèi)容請(qǐng)關(guān)注PHP中文網(wǎng)(www.miracleart.cn)!