Monday, 9 June 2014
Jquery Basic form Validation
Jquery:
Jquery is a java script library provides much more ready made features. Main motto of jquery is write less, do more.
Simle form Validation:
step 1:
Create HTML form and include fallowing jquery libraries.
1. jquery-2.1.1.min.js(jquery main library)
2. jquery.validate.min.js(jquery validation plugin library)
3. customjq.js (This is js having common validation methods)
html form file:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JQUERY DEMO</title>
<script type="text/javascript" src="./js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="./js/jquery.validate.min.js"></script>
<script type="text/javascript" src="./js/customjq.js"></script>
<link rel="stylesheet" type="text/css" href="./css/font.css">
</head>
<body>
<form id="myform">
<div align="left" class="large">
<H1>JQUERY DEMO</H1>
</div>
<div align="center" class="small">
<table width="40%" height="100%">
<H2>Employee Details</H2>
<tr>
<td align="left">Email ID:
<td><input type="text" name="field1" class="input1" /> <br /></td>
</tr>
<tr>
<td align="left">User Name:</td>
<td><input type="text" name="field2" class="input1" /></td>
</tr>
<tr>
<td align="left" nowrap="nowrap">Mobile Number:</td>
<td><input type="text" name="field3" class="input1" /></td>
</tr>
<tr>
<td align="left"><input type="submit" name="Submit"
value="Validate" />
<td>
</tr>
</table>
</div>
</form>
</body>
</html>
customjq.js
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
rules : {
field1 : {
required : true,
email : true
},
field2 : {
required : true,
minlength : 5
},
field3 : {
required : true,
number : true,
minlength : 10
}
},
messages : {
"field1" : {
required : "Please Enter Valid Email ID"
},
"field2" : {
required : "Please Enter Valid User Name"
},
"field3" : {
required : "Please Enter Valid Mobile Number",
number : "Please enter numbers only"
},
},
submitHandler : function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
out put:
There are three fields for validation email,username and mobile number. For email validation no need to write our own logic as we are doing in java script since this feature is already implemented in jquery library just we have to make use of this by declaring email:true. Similary for number validation we can use number:true. Using message section as shown above we can declare custom user defined validation messages.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment