Home > Article > Web Front-end > Simple example of form validation using HTML5_html5 tutorial tips
HTML5 provides the pattern attribute for form elements, which accepts a regular expression. When the form is submitted, this regular expression will be used to verify that the value in the form is not empty. If the value of the control does not match this regular expression, a prompt box will pop up and the expression will be prevented from being submitted. The text in the prompt box can be customized using the setCustomValidity method.
For example, in the form below, the text box only accepts mainland mobile phone numbers. If you enter other things, you cannot submit it
Run
Note that only non-empty forms will use regular validation. If nothing is entered, the pattern will not be used, so required assistance is required. But the prompt that pops up from this code is like this:
Only monkeys can understand such prompt text! So we also need more friendly prompt text, defined using the setCustomValidity method.
Run
invalid事件会在表单submit事件之前触发,如果验证不通过的话就不会触发表单的submit。而提交时会先验证所有表单元素是值是否有效。除了提交外还可以手动调用checkValidity方法来执行验证。
上面的例子中我直接对控件设置固定的提示其实不太好,有时候可能需要更详细的提示信息,比如空的时候提示为空、太长的时候提示太长、非数字的时候提示非数字等。这些动作可以通过程序验证后动态地setCustomValidity来实现。
其实我觉得HTML5的这套API设计的很糟糕,虽然可以满足基本需求,但还真不太实用。
手机页面中表单提交用JavaScript验证信息 会弹出窗口,用户体验极差,所以再给出一个手机端用HTML5的属性来验证的示例: