Data Validation – How to Validate Forms using HTML5

Data Validation – How to Validate Forms using HTML5

20 82790
Data Validation – How to Validate Forms using HTML5

Data Validation with HTML5. Today I will tell about data validation again. HTML5 specification bring us many interesting, and one of useful function is browser-based form validation. Of course, not all browsers support HTML5 (even IE9 not support it yet), but as example Firefox 4 started support it. And this is great, it can mean that shortly many of existed members of Firefox will update its browsers and will have HTML5 support. Of course, we always can use Javascript to validate our fields (even jQuery libraries), but what if in coming future we even don`t will worry about it at all? What if most of work will execute our web browser? Future coming today.

Here are our sample and downloadable package:

Live Demo

Ok, download the example files and lets start coding !


Step 1. HTML

This is our main source file with our form. I decided to create some ‘Join form’ to website using HTML5:

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="stylesheet" href="css/main.css" type="text/css" media="all" />
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>
<div class="example">
<form action="#" method="post" enctype="multipart/form-data">
<fieldset>
<legend>General Info</legend>
<div class="required">
<label for="username">Username:</label>
<input type="text" required x-moz-errormessage="Enter Username" name="username" id="username" class="inputText" size="10" maxlength="128" value="" />
</div>
<div class="required">
<label for="first_name">First Name:</label>
<input type="text" required x-moz-errormessage="Enter First Name" name="first_name" id="first_name" class="inputText" size="10" maxlength="128" value="" />
</div>
<div class="required">
<label for="last_name">Last Name:</label>
<input type="text" required x-moz-errormessage="Enter Second Name" name="last_name" id="last_name" class="inputText" size="10" maxlength="128" value="" />
</div>
<div class="required">
<label for="password">Password</label><input type='password' id='p1'><br /><br />
<label for="password">Confirm Password</label><input type='password' onfocus="validatePass(document.getElementById('p1'), this);" oninput="validatePass(document.getElementById('p1'), this);"> 
</div>
<div class="required">
<label for="email">Email:</label>
<input type='email' required pattern=".*@gmail\.com" x-moz-errormessage="Enter your email (gmail.com)" name="email" id="email" class="inputText" size="10" maxlength="128" value="" />
</div>
</fieldset>
<fieldset>
<legend>Miscellaneous Info</legend>
<div class="required">
<label for="profile_type">Select</label>
<select required x-moz-errormessage="Select Your Profile Type" name="profile_type" id="profile_type" size="1">
<option value=""></option>
<option value="single">Single</option>
<option value="couple">Couple</option>
</select>
</div>
<div class="optional">
<label for="sex">Sex:</label>
<input type="radio" required x-moz-errormessage="Select Your Sex" name="sex" id="sex" value="male" /> Male 
<input type="radio" required x-moz-errormessage="Select Your Sex" name="sex" id="sex" value="female" /> Female
</div>
<div class="optional">
<label for="phone">Phone:</label>
<input type="tel" required pattern='\d\d\d \d\d\d \d\d\d\d\d\d' x-moz-errormessage="Enter your Phone number in format 'xxx xxx xxxxxx'" class="inputText" size="10" maxlength="50" value="" />
</div>
<div class="optional">
<label for="url">Website:</label>
<input type="url" required x-moz-errormessage="Enter Your Website URL starting with http://" class="inputText" size="10" maxlength="128" value="" />
</div>
<div class="required">
<label for="description">Description:</label>
<textarea required name="description" id="description" class="inputTextarea" rows="3" cols="51"></textarea>
</div>
<div class="optional">
<label for="image">Upload photo:</label>
<input type="file" required x-moz-errormessage="Select image file" name="image" id="image" class="inputFile" />
</div>
<div class="optional">
<label for="agreement">Subscription:</label>
<input type="checkbox" name="subscribe" id="subscribe" value="yes" /> Subscribe to our news
</div>
<div class="required">
<label for="agreement">Agreement:</label>
<input type="checkbox" required x-moz-errormessage="Need Check It" name="agreement" id="agreement" value="yes" /> I have read and agreed with Terms of Use.
</div>
</fieldset>
<fieldset>
<div class="submit">
<div>
<input type="submit" class="inputSubmit" value="Join Now" />
</div>
</div>
</fieldset>
</form>
<div style="clear:both"></div>
</div>

Here are important notes. HTML5 using several new attributes as rules for validation of form fields. This is:

  • required – this attribute will transform field into required field. This attribute applicable to different form elements (input, select, textarea etc). So if we will mark our field with this attribute, it will mean that we will need to check our checkbox field, type value for text field, select value from selector etc.
  • pattern – this attribute will determinate regular expression which will using for checking values of elements. In our example I will use this attribute to set custom pattern for email and phone fields.
  • maxlength – we can use this attribute to set max limit of symbols for field.

Step 2. CSS

All styles here:

css/main.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.example{background:#FFF;width:700px;font-size:80%;border:1px #000 solid;margin:10px auto;padding:1em 2em 2em;-moz-border-radius: 3px;-webkit-border-radius: 3px}
form{font-size:100%;min-width:560px;max-width:620px;width:590px;margin:0 auto;padding:0}
form fieldset{clear:both;font-size:100%;border-color:#000;border-style:solid none none;border-width:1px 0 0;margin:0;padding:10px}
form fieldset legend{font-size:150%;font-weight:400;color:#000;margin:0;padding:0 5px}
label{font-size:100%}
label u{font-style:normal;text-decoration:underline}
input,select,textarea{font-family:Tahoma, Arial, sans-serif;font-size:100%;color:#000}
textarea{overflow:auto}
form div{clear:left;display:block;width:354px;zoom:1;margin:10px 0 0;padding:1px 3px}
form div fieldset{clear:none;width:197px;border-color:#666;border-style:solid;border-width:1px;margin:0 0 0 144px;padding:0 5px 5px}
form div fieldset legend{font-size:100%;padding:0 3px 0 9px}
form div label{display:block;float:left;width:130px;text-align:right;margin:0 0 5px;padding:3px 5px}
form div.optional label,label.optional{font-weight:400}
form div img{float:left;border:1px solid #000;margin:0 0 5px}
form div input.inputFile{width:211px}
form div.submit{width:214px;padding:0 0 0 146px}
form div.submit div{display:inline;float:left;text-align:left;width:auto;margin:0;padding:0}
form div.required fieldset legend,form div.required label,label.required{font-weight:700}
form div select,form div textarea,form div input.inputText,form div input.inputPassword{width:200px;margin:0;padding:1px 3px}
:valid {box-shadow:  0 0 5px green}
:-moz-submit-invalid {box-shadow:  0 0 5px pink}

News: CSS3 UI represents us new pseudo-classes (uses in HTML5), as example :invalid, :valid, :required and : optional. Firefox 4 support all these pseudo-classes and add own new pseudo-class :-moz-submit-invalid. This class applied to the button ‘submit’ when form contain any invalid elements.

Step 3. JS

We will using one easy function for password validation in this file

js/main.js

function validatePass(p1, p2) {
if (p1.value != p2.value || p1.value == '' || p2.value == '') {
p2.setCustomValidity('Password incorrect');
} else {
p2.setCustomValidity('');
}
}

Using custom JS we can apply own validation methods for custom elements. As example – we will using this to validate of password field (second field – confirm password field). So, we can mark element is invalid using setCustomValidity method. As first param – it accept text (error message). Just check this function ‘validatePass’ to understand what it doing.


Live Demo

Conclusion

Very hope that HTML5 will supported by most of browsers soon. Just because it will give us possibility to make really user friendly forms. But anyway, even if this will allow us to validate data, never forgot to check received data at server side before working (especially before inserting to database). Never trust all incoming data – it will protect you from any unexpected cases. Good luck!

SIMILAR ARTICLES

Bootstrap Forms

0 5
jQuery Mobile Lesson 6

0 5

20 COMMENTS

  1. I don’t see any mention of server-side validation. Client-side is nice, but server-side is ALWAYS essential unless you don’t REALLY need to validate anything. You never know if a user has Javascript or not…

    • 2 Jeremy,
      No, for server validation you can`t use javascript of course (javascript working only at client side). For server validation you should to use PHP as example (or any another server language which you using, Perl, C++ as example)
      Are you, someone else interested in server-side safe validation? I can prepare this if you like

  2. I am trying to learn HTML5 and I would like to use the “pattern” input keyword to validate the input as the user types it (e.g. validation after pressing tab or changing focus from input box).

  3. Helpful info. Fortunate me I found your site accidentally, and I’m surprised why this twist of fate didn’t happened earlier!
    I bookmarked it.

    • Hello Akki,
      Then – you can validate it as usual text field. As I know – full name is a combination of first name and second name.

  4. This stuff is really cool, thanks for the nice article.

    Though everything working as expected on Firefox(ver 21), have some issues in chrome(not tested in IE though).
    1. Aura effect(Red n Green border) is missing for textfields.
    2. Custom error messages are not applied, giving a common message like ‘Please fill out this field’

    Is there any way to achieve background border and unique behavior for all modern HTML5 browsers?

    • Hello Nag,
      Unfortunately we can not set a custom value in Chrome browser, however you can add the ‘title’ attribute to highlight a necessary message.

  5. I thought the header for HTML5 would be something like:

    etc…

    But you have a lot of legacy junk up there.

    Also, validation is not treated equally in all browsers. That is probably why you also need to include server side validation. Also, someone could spoof your form on another server and post junk to your server (unless you have proper protection in place). Client side validation is great for helping users enter correct data, but is not enough to keep hackers away. :)

    • Hello Jay,
      Agree, we never should neglect with the validation on server side. This is always essential. Two years ago I just described how to perform the client-side validation (to prevent an unnecessary form posting until you have any errors on your form)

  6. Hi i need how to do form validation using jquery with datepicker and some images??? can u pls say about that?? :(

  7. I searched google to know about form data validation and fortunately found this piece of good tutorials online. (Your post is on first page of Google search.) Thanks Andrew for this tut.

Leave a Reply