Sunday, May 30, 2010

how to validate textbox using javascript


How to validate text box/textarea in Java Script?



Following example shows you how to validate text box or textarea in your web application

When filling forms, you may have seen there are some required fields to fill before you submit the form. If you are forget to fill such a field, you will be asked to fill that field to complete the process. Most of web application validate these fields as client side validation. That means they use JavaScript to validate user inputs. As an example there are two text boxes in your form called first name and last name, So you want that user to fill these fields, before they submit the form. Here is an example how to write validation script for that.


Also you can use input data validation to force user to enter appropriate data type. For a example if there is a text field in the form to enter the users age. So that the age should be non-negative number and most occasions it is less than 100. So you need to check if the user has entered the correct integer value for age field, that means check is it a number. Keep it mind to limit the user inputs to specific number of characters. You can use the attribute maxlength to limit the input characters. In most cases when you prompt for age as an input you can set maxlength to 2. You can do these validation events such as onclick, mouse over, on change, etc.

Note: You can select the error display method using provided drop down.


1. Validate textbox when user clicks on submit button

Example : This example describes you how to validate first name and last name. There are five error display options for you. Select your preferred method to validate your text box.

Syntax: <input name="Button" type="button" value="Submit" onclick="javascript:validate_textbox1(this.form);" />


onclick event of the button
First Name 
Last Name 
Error Display Type

Copy and paste bellow code for validate textbox

<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

function validate_textbox1(e) {

var t = parseInt(e["err_msg_type"].value);

if(isEmptyTextBox(e["firstName"], "Please enter First Name", t, "first_name_info")) {

return false

}

if(isEmptyTextBox(e["lastName"], "Please enter Latst Name", t, "last_name_info")) {

return false

}

return true

}

function isEmptyTextBox(e, t, n, r) {

var i = document.getElementById(r);

if(e.value.replace(/\s+$/, "") == "") {

i.className = ""

switch(n) {

case 0:

{

i.innerHTML = "";

alert(t)

}

break;

case 1:

{

i.innerHTML = t

}

break;

case 2:

{

i.innerHTML = "";

e.className = "err_tb1"

}

break;

case 3:

{

i.innerHTML = "";

e.className = "err_tb2"

}

break;

case 4:

{

i.innerHTML = "*";

e.className = "tb"

}

break;

case 5:

{

i.innerHTML = "&nbsp;&nbsp;&nbsp;";

i.className = "custom_error"

}

break

}

e.value = "";

e.focus();

return true

}

else {

if(n == 5) {

i.innerHTML = "&nbsp;&nbsp;&n";

i.className = "error_free"

}

else {

i.innerHTML = "";

i.className = ""

}

e.className = "tb";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_0" name="text_box_validation_0" action="#" method="post">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">onclick method of the button</td>

</tr>

<tr>

<td align="right">First Name</td>

<td>

<input name="firstName" type="text" class="tb" id="firstName" maxlength="50" />

<label id="first_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Last Name</td>

<td>

<input name="lastName" type="text" class="tb" id="lastName" maxlength="50" />

<label id="last_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td></td>

<td>

<input name="Button" type="button" value="Submit" onclick="javascript:validate_textbox1(this.form);" />

</td>

<td></td>

</tr>

<tr>

<td align="right">Error Display Type</td>

<td colspan="2"><select name="err_msg_type" id="err_msg_type">

<option value="0">Alert box</option>

<option value="1">Text message</option>

<option value="2">Change textbox border color</option>

<option value="3">Change textbox background color</option>

<option value="4">Display Star</option>

<option value="5">Custom Style</option>

</select></td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>

</tr>

</tbody>

</table>

</form>

</body>

</html>




2. Validate textbox - onblur method of the textbox

Example : This example explains you how to set validation for textbox or textare as onblur event of the element.

Syntax: <input name="lastName2" type="text" class="tb" id="lastName2" maxlength="50" onBlur="javascript:validate_textbox2(this,'Please enter Last Name','last_name_info2');" />

onblur event of the textarea or textbox
First Name 
Last Name 
Error Display Type

Copy and paste bellow code for validate textbox


<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

function validate_textbox2(text_box,message,lbl) {

var t = parseInt(document.getElementById("err_msg_type").value);

if(isEmptyTextBox2(text_box,message, t, lbl)) {

return false

}

return true

}

function isEmptyTextBox2(e, t, n, r) {

var i = document.getElementById(r);

if(e.value.replace(/\s+$/, "") == "") {

i.className = ""

switch(n) {

case 0:

{

i.innerHTML = "";

alert(t)

}

break;

case 1:

{

i.innerHTML = t

}

break;

case 2:

{

i.innerHTML = "";

e.className = "err_tb1"

}

break;

case 3:

{

i.innerHTML = "";

e.className = "err_tb2"

}

break;

case 4:

{

i.innerHTML = "*";

e.className = "tb"

}

break;

case 5:

{

i.innerHTML = "&nbsp;&nbsp;&nbsp;";

i.className = "custom_error"

}

break

}

e.value = "";

e.focus();

return true

}

else {

if(n == 5) {

i.innerHTML = "&nbsp;&nbsp;&nbsp;";

i.className = "error_free"

}

else {

i.innerHTML = "";

i.className = ""

}

e.className = "tb";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_1" name="text_box_validation_1" action="#" method="post">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">onclick method of the button</td>

</tr>

<tr>

<td align="right">First Name</td>

<td>

<input name="firstName" type="text" class="tb" id="firstName" maxlength="50" onBlur="javascript:validate_textbox2(this,'Please enter First Name','first_name_info2');" />

<label id="first_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Last Name</td>

<td>

<input name="lastName" type="text" class="tb" id="lastName" maxlength="50" onBlur="javascript:validate_textbox2(this,'Please enter Last Name','last_name_info2');" />

<label id="last_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<!--<tr>

<td></td>

<td>

<input name="Button" type="button" value="Submit"/>

</td>

<td></td>

</tr>-->

<tr>

<td align="right">Error Display Type</td>

<td colspan="2"><select name="err_msg_type" id="err_msg_type">

<option value="0">Alert box</option>

<option value="1">Text message</option>

<option value="2">Change textbox border color</option>

<option value="3">Change textbox background color</option>

<option value="4">Display Star</option>

<option value="5" selected>Custom Style</option>

</select></td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>

</tr>

</tbody>

</table>

</form>

</body>

</html>



3. Validate user name and password - onsubmit event of the form

This code sample shows you how to validate textfield at the onsubmit event of the form. If user forgot to enter values for required fields, He will be prompt to enter them before submit the form.

Syntax: <form id="text_box_validation_3" name="text_box_validation_3" action="#" method="post" onSubmit="javascript:return validate_login();">

onsubmit event of the form
User Name 
Password 
  
Copy and paste bellow code for validate textbox


<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

function validate_login()

{

var e = 0;

if(isEmpty("user_name", "Please enter User Name", "user_name_info"))

{

e++

}

if(isEmpty("password", "Please enter Password", "password_info"))

{

e++

}

if(e > 0)

{

alert("Please fill login details");

return false

}

else

{

return true

}

}

function isEmpty(e, t, n)

{

var r = document.getElementById(e);

var n = document.getElementById(n);

if(r.value.replace(/\s+$/, "") == "")

{

n.innerHTML = t;

r.value = "";

r.focus();

return true

}

else

{

n.innerHTML = "";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_3" name="text_box_validation_3" action="#" method="post" onSubmit="javascript:return validate_login();">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">onsubmit event of the form</td>

</tr>

<tr>

<td align="right">User Name</td>

<td>

<input name="user_name" type="text" class="tb" id="user_name" maxlength="50" />

<label id="user_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Password</td>

<td>

<input name="password" type="password" class="tb" id="password" maxlength="50" />

<label id="password_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td></td>

<td>

<input name="btnLogin" type="submit" value="Login" id="btnLogin"/>

</td>

<td></td>

</tr>

<tr>

<td align="right">&nbsp;</td>

<td colspan="2">&nbsp;</td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>


</tr>

</tbody>

</table>

</form>

</body>

</html>



4. Validate integer values - onkeyup event of the textbox

In this example you can learn how to validate textbox in javascript at the vent of onkeyup. That means if you type incorrect value for the age field, it alerts you to enter a correct value for age. Also there is an example for validate textarea. There user have to enter at least 20 characters to the description field.

Syntax: <input name="age" type="text" class="tb" id="age" size="5" maxlength="50" onKeyUp="javascript:is_valid_integer(this);" />

Validate textbox and textare
Age 
Description
(Minimum 20 characters)
 
  
Copy and paste bellow code for validate textbox
and textarea.

<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

var reg = /^[0-9]+$/;

function is_valid_integer(textField){

if(!reg.test(textField.value)){

alert("Please enter integers only");

textField.value="";

textField.focus();

return false;

}

}

function validate_form(){

var e = 0;

if(isEmpty("age", "Please enter Age", "age_info") || !reg.test(document.getElementById("age").value)){

e++

}

if(isEmpty("description", "Please enter Description", "description_info")){

e++

}else{

if(document.getElementById("description").value.length<20){

document.getElementById("description_info").innerHTML="Minimum 20 Characters";

e++

}

}

if(e > 0){

alert("Please fill form details correctly");

return false

}else{

return true

}

}

function isEmpty(e, t, n)

{

var r = document.getElementById(e);

var n = document.getElementById(n);

if(r.value.replace(/\s+$/, "") == "")

{

n.innerHTML = t;

r.value = "";

r.focus();

return true

}

else

{

n.innerHTML = "";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_4" name="text_box_validation_4" action="#" method="post" onSubmit="javascript:return validate_form();">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">Validate textbox and textare</td>

</tr>

<tr>

<td align="right">Age</td>

<td>

<input name="age" type="text" class="tb" id="age" size="5" maxlength="50" onKeyUp="javascript:is_valid_integer(this);" />

<label id="age_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Description<br/>(Minimum 20 characters)</td>

<td><textarea name="description" cols="30" rows="5" class="tb" id="description"></textarea><br/>

<label id="description_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td></td>

<td>

<input name="btnSubmit" type="submit" value="Submit" id="btnSubmit"/>

</td>

<td></td>

</tr>

<tr>

<td align="right">&nbsp;</td>

<td colspan="2">&nbsp;</td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>

</tr>

</tbody>

</table>

</form>

</body>

</html>