Friday, 4 October 2013

Automatic client-side validation using the HTML5 'pattern' attribute

The new "pattern" attribute defined in HTML5 facilitates automatic validation of a textbox value by allowing the developer to define a Regular Expression pattern for the field. On form submission, the input value is validated against the pattern, and if the validation fails, the browser highlights the field and shows an error message.
Let's see an example that illustrates all this:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Pattern attribute example</title>
<label id="pincode">Pin Code:</label>
<!--"required" attribute makes input mandatory in an input element -->
<input type="text" id="pincode" name="pincode"
pattern="^[1-9][0-9]{5}$" required
title="A six digit number that doesn't begin with zero.">
<br /> <br />
<button type="submit">Submit</button>

Running the above code in the Google Chrome browser gives me the following screenshot:

No comments:

Post a Comment