How to use constraint validation API in H5

php中世界最好的语言
Release: 2018-03-26 13:53:31
Original
2604 people have browsed it

This time I will show you how to use the constraint verification API in H5. What are theprecautions for using the constraint verification API in H5? The following is a practical case, let's take a look.

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 many native validations for data formats support, for example:

Copy after login
When you click the submit button, if the format you enter does not conform to the email, it will not be submitted, and the browser will prompt you

error message.

For example, under chrome:

Note:

1. It will only be triggered when you submit Browser verification

2. Different browsers have different behavior styles of prompt information

3. When multiple inputs do not meet the requirements, only an error will be prompted, and the form will generally be prompted. The

of the relatively earlier Input should not be taken for granted. When the input 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 prompt an error when submitting. Information, type='tel' only plays a semantic role on the PC side. On the mobile side, the generated keyboard can be a pure numeric keyboard, which 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):

Copy after login
When you click submit, if the data you enter does not conform to the regular format in pattern, the browser will block the form. Submit, and prompt: '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

Like 'Please match the requested format The browser prompt information string "Be consistent" is hidden in the validationMessage attribute of the input DOM object. This attribute is read-only in most modern browsers, that is, it cannot be modified, such as the following code:

Copy after login
When submitting, if the Input content is empty, the browser will prompt 'Please fill in this field'. We can print this sentence out on the console:

var input = document.getElementById('input') input.validationMessage // =>'请填写此字段'
Copy after login
If you want to modify the content, You can call the setCustomValidity interface to change the value of validationMessage

input.setCustomValidity('这个字段必须填上哦'); // 下面这种做法适用于不支持setCustomValidity的浏览器,基本现代浏览器都不支持这样做 input.validationMessage = '这个字段必须填上哦'
Copy after login
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

HTML

Form ValidationThe system uses the validationMessage attribute to detect whether the data in the text box passes verification. If its value is an empty string, If it indicates that the verification has passed, otherwise, it indicates that it has not passed, and 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.

Simple example of constraint verification API

约束验证API是在原生方法之上更灵活的表达方式,你可以自己设置数据是否通过,而不借助于正则表达式。原理很简单,通过if判断,如果数据格式使你满意,那么你就调用setCustomValidity使validationMessage的值为空,否则,你就调用setCustomValidity传入错误信息:

input.addEventListener('input', function () { if(this.value.length > 3){ // 判断条件完全自定义 input.setCustomValidity('格式不正确'); }else { input.setCustomValidity('') } });
Copy after login

每次键盘输入,代码都会判断格式是否正确,然后调用setCustomValidity设置validationMessage的值。不要妄想每按下键浏览器都会提示你结果是否正确,浏览器只有在点击提交按钮的时候才会提示validationMessage里的值(如果有的话)。

如果你还没有走思的话,一定会问,既然这样,为什么要为input绑定键盘事件,每输入一下都要进行判断呢?直接为表单绑定提交事件,在提交时再判断多好,别急,这么做是有好处的。

随着输入判断格式与样式

作为用户,我们当然想在得知我输入了错误的格式之后,文本框变红(或者有别的提示)。而在我每次输入一个字符,如果对了,文本框就恢复正常。我们可以使用CSS伪类来实现这个功能:

input:required { background-color: #FFE14D; } /*这个伪类通过validationMessage属性进行判断*/ input:invalid { border: 2px solid red; }
Copy after login

上面的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采用事件捕获的方式处理之。这样,就大功告成了。

最终实例

好了,现在是时候总结一下我们所学的知识并创造最佳实践了:

    form  
Copy after login

运行后截图如下:

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

H5表单验证有哪些方法

移动端H5页面端怎样除去input输入框的默认样式

The above is the detailed content of How to use constraint validation API in H5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!