Friday, 27 August 2010

Form validation using jQuery

The code below offers a simple example, which you can build upon, of using jQuery to validate your forms. I have added a few comments in green to explain what is going on.

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validate form</title>
<!-- Get jQuery from Google -->
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<!-- Get the validation library from Microsoft -->
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
/* apply validation rules to myform */
$("#myform").validate(
{
rules:
{
/* apply a simple rule to contactname */
contactname: "required",
/* apply more rules to email */
email:
{
required: true,
email: true
}
},
/* provide special messages to contactname */
messages:
{
contactname: "Please enter a contact name"
}
});
});
</script>
<style type="text/css">
body
{
font-family:sans-serif;
}
</style>
</head>
<body>
<form method="post" action="" id="myform">
<label for="name">Name:</label>
<!-- Adding the class "required" works makes coincides with the jQuery call for this field -->
<input type="text" size="20" name="contactname" id="contactname" value="" class="required" /><br />
<label for="email">Email:</label>
<!-- Adding the class "required email" works makes coincides with the jQuery call for this field -->
<input type="text" size="20" name="email" id="email" value="" class="required email" /><br />
<label for="message">Message:</label>
<!-- No validation required for the message -->
<textarea rows="5" cols="20" name="message" id="message"></textarea><br />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>

No comments:

Post a Comment