Let us start with a simple example. Our demonstration form contains four fields: name, e-mail, comment and URL. As you can see, the first three fields are required, whereas the URL field is optional. If you submit the form without filling in the required fields, you will be prompted with an error message.
Here is the code we used for the form in the demonstration above.
The code is quite straightforward and doesn't need much explanation. However, there are a few important points that I would like to bring to your attention.
<html>
<head>
<title>Simple Form Validation</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/
validate/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required",// simple rule, converted to {required:true}
email: {// compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
input[type=text], textarea { width: 250px; float: left; }
textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL</span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
</form>
</body>
</html>
Now, let us see the validate() function in detail.All we are doing here is initializing the validation of the form using the validate() function. It can take several parameters. In the example above, we use only two of them, but you can find a list of all the options for the validate() function at :
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", // simple rule, converted to {required: true}
email: { // compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
You can find an exhaustive list of built-in validation methods at Demo
If you have better solution, just tell me !
0 comments:
Post a Comment