Almost all of us know how to do a JavaScript validation, but you know there is a simple way to validate a form using HTML5?
Yes, it’s true but many of us does not know validation can be done in HTML5 itself, this tutorial I’m going to show you is a simple example of how to do make all the fields mandatory.
Let’s see the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<!DOCTYPE html> <html> <head> <style> div{ width: 410px; padding: 10px; } label{ width: 100px; float:left; } input{ width: 300px; } #submit{ float:right; width: 100px; margin-right: 10px; } </style> </head> <body> <h2>Simple HTML5 Form Validation Demo - Tutorialsmade.com</h2> <form action="" method="post"> <div> <label for="name">Name:</label> <input type="text" id="name" name="name" required /> </div> <div> <label for="email">Email:</label> <input type="email" name="email" required /> </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password" required /> </div> <div> <label for="websiteurl">Website URL:</label> <input type="url" id="websiteurl" name="websiteurl" required /> </div> <div> <label for="quantity">Quantity:</label> <input type="number" id="quantity" name="quantity" required min="1" max="5" /> </div> <div> <input type="submit" value="Submit" id="submit"> </div> </form> </body> </html> |
You got something after reading the code?
If not, I will tell you what, there are new set of input types and attributes introduced in HTML5, using that we can do all kind of form validations, in the above example if you see I have added few new input types such as,
input=”email”
input=”url”
input=”number”
and an attribute called “required” in all the fields.
So just adding a required attribute makes all the fields mandatory and the new input types validates if you not entered a valid email, url or a number in the respective fields.
You can also validate a field using regular expression using a new attribute called “pattern”
For instance, If you want to validate the name field, lets say you want at least three characters should be typed in the name field, I can add a reg ex patter there like below:
1 |
<input type="text" id="name" name="name" required pattern="\w{3,}" /> |
See the demo in here: