开发者

Are there any JavaScript properties related to web browser form validation in HTML5?

In HTML5, the client side validation should become a job of the web browser, via attributes like pattern or required.

Is there only a CSS implementation of this (i.e开发者_运维问答. the :valid and :invalid selectors, to give feedback to the user) or is there also a JavaScript implementation?

I’m thinking of something like a feature allowing a JavaScript function to get called if the user clicks submit and the form has invalid values in it. Or a flag that I can access in the form object to show if it has errors or not.

Thanks.


Yes, there is a validity attribute you can query. See http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#dom-cva-validity

I've no idea how much support for this exists in browsers currently.


Yes, it does, and it currently works. See A List Apart's excellent article on the subject by Ryan Seddon. According to the article, Chrome 4+, Safari 5+ and Opera 9.6+ all support the properties. (He also includes an example.)

Quoting from the article, you can do things like:

input:focus:required:invalid {
  background: pink url(ico_validation.png) 379px 3px no-repeat;
}
input:required:valid {
  background-color: #fff;
  background-position: 379px -61px;
}

And when an input validates it will display one icon, and when it is invalidated and focused it will display another.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜