Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a way to check validity of HTML5 forms?

Is it possible to check if an input element of an html5 form is valid based on the pattern I set for it? I know the psuedo class stuff.. but i'm hoping something like: document.getElementById('petitionName').valid can return true or false..

I really hope I don't need to create javascript to re-verify this stuff.

like image 827
Henry Avatar asked May 01 '11 04:05

Henry


People also ask

How does HTML5 validation work?

HTML5 validation kicks in when the form is submitted (user clicks the Submit button). When this happens, the browsers starts going through its list of required inputs and prompts when the input is missing on the required inputs.

How do I check if a form is valid in HTML5?

The simplest HTML5 validation feature is the required attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.


2 Answers

there are two ways to check the validity.

  1. inputElement.checkValidity() returns true or false
  2. inputElement.validity returns the validity-state object. inputElement.validity.valid returns true/false

Instead of using keyup, you can also use the 'input' event. All browser, which have implemented the constraint validation API, have also implemented the input-event.

If you are using option 1 above, Opera has a bug here and will show its validation hint. So you should use 2.

I have created a html5 forms library, which implements all unknown features to incapable browsers + fixes issues in HTML5 browsers. So everything works like defined in the spec, but it's built on top of jQuery. (http://afarkas.github.com/webshim/demos/index.html).

like image 116
alexander farkas Avatar answered Sep 20 '22 01:09

alexander farkas


You can use the pattern attribute.

It will validate it client side, so no need to validate it again client side.

Example

jsFiddle.

But, make sure you do it again server side.

Also note, because browser compatibility is quite poor right now, JavaScript is the norm for validating client side.

like image 30
alex Avatar answered Sep 21 '22 01:09

alex