Monday, February 11, 2013

Simple Validation Form In Jquery


Preview On Focus:



Preview On Button Click:



Below is our HTML form with one text box and the validation messages.

<form id="form1" runat="server">
<fieldset class="formContainer">
<h3>Simple Validation Form.</h3>
<div class="rowContainer">
<label for="txtFirstname">Choose a username</label>
<input id="txtFirstname" type="text"/>
<div class="tooltipContainer info">Minimum 4 characters, maximum 15 characters.</div>
<div class="tooltipContainer error">Username must be between 4 and 15 characters.</div>
</div>
<input type="button" id="btnSubmit" value="Sign in" onclick="validateForm()"/>
</fieldset>
</form>
Add the form style.
<style type="text/css">
body
{
font-family:Arial, Sans-Serif;
font-size:83%;
}
.formContainer
{
background-color:#F5EFC9;
border:none;
padding:30px;
}
.formContainer h3
{
margin:0px;
padding:0px 0px 10px 0px;
font-size:135%;
}
.rowContainer
{
width:100%;
overflow:hidden;
padding-bottom:5px;
height:34px;
}
.rowContainer label
{
width:140px;
float:left;
color: #758656;
font-weight:bold;
}
.rowContainer input[type="text"]
{
width:200px;
}
.tooltipContainer
{
height:16px;
font-size:11px;
color: #666666;
display:none;
float:none;
background-repeat:no-repeat;
background-position:left center;
padding:0px 20px;
}
.info
{
background-image:url('info.gif');
}
.error
{
background-image:url('error.gif');
}
</style> 
Add the Jquery script to validate the form.
<script type="text/javascript">
$(document).ready(function () {
$(".formContainer input[type=text]").focus(function () {
$(this).parent().find(".error").css("display", "none");
$(this).parent().find(".info").css("display", "block");
}).blur(function () {
$(this).parent().find(".info").css("display", "none");
});
});
function validateForm() {
$(".formContainer input[type=text]").each(function () {
var text = $(this).attr("value");
if (text == "") {
$(this).parent().find(".error").css("display", "block");
}
if (text.length < 5) {
$(this).parent().find(".error").css("display", "block");
}
});
}
function clearForm() {
$(".formContainer input[type=text]").each(function () {
$(this).parent().find(".error").css("display", "none");
});
}
</script>

No comments:
Write comments
Recommended Posts × +