简体   繁体   中英

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM