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(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi81_kukVYhnzttb4EdcAbs9J1PvYJ1wusYwmy_a7b213KlbOW4G-T2qAajx1QVHjgHfLN62ntZ4lKT_ErLUBgpiX0_3CYy25sdjJokRD-hMUcOs8TPh_YSih5HqZTEl0yx4ANlDBeqEKU/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFeVyTTFnxLa2MB-wcZ-xo-BcpQGA5e7YofiZHBESoU8HjmIVU_J4Q_fORFyGAIBSRG-JiF0fzk3geu5HQRQoeAVI6VQ_-glJ_GuD68ROZKP2Aad03ZN-nWSqoy5WHdO2K6_YOKSkEfVM/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(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi81_kukVYhnzttb4EdcAbs9J1PvYJ1wusYwmy_a7b213KlbOW4G-T2qAajx1QVHjgHfLN62ntZ4lKT_ErLUBgpiX0_3CYy25sdjJokRD-hMUcOs8TPh_YSih5HqZTEl0yx4ANlDBeqEKU/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFeVyTTFnxLa2MB-wcZ-xo-BcpQGA5e7YofiZHBESoU8HjmIVU_J4Q_fORFyGAIBSRG-JiF0fzk3geu5HQRQoeAVI6VQ_-glJ_GuD68ROZKP2Aad03ZN-nWSqoy5WHdO2K6_YOKSkEfVM/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(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi81_kukVYhnzttb4EdcAbs9J1PvYJ1wusYwmy_a7b213KlbOW4G-T2qAajx1QVHjgHfLN62ntZ4lKT_ErLUBgpiX0_3CYy25sdjJokRD-hMUcOs8TPh_YSih5HqZTEl0yx4ANlDBeqEKU/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFeVyTTFnxLa2MB-wcZ-xo-BcpQGA5e7YofiZHBESoU8HjmIVU_J4Q_fORFyGAIBSRG-JiF0fzk3geu5HQRQoeAVI6VQ_-glJ_GuD68ROZKP2Aad03ZN-nWSqoy5WHdO2K6_YOKSkEfVM/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(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi81_kukVYhnzttb4EdcAbs9J1PvYJ1wusYwmy_a7b213KlbOW4G-T2qAajx1QVHjgHfLN62ntZ4lKT_ErLUBgpiX0_3CYy25sdjJokRD-hMUcOs8TPh_YSih5HqZTEl0yx4ANlDBeqEKU/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFeVyTTFnxLa2MB-wcZ-xo-BcpQGA5e7YofiZHBESoU8HjmIVU_J4Q_fORFyGAIBSRG-JiF0fzk3geu5HQRQoeAVI6VQ_-glJ_GuD68ROZKP2Aad03ZN-nWSqoy5WHdO2K6_YOKSkEfVM/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>



15 comments:

Anonymous said...

like this also we can do validation. http://aspnettutorialonline.blogspot.com/2012/05/textbox-numeric-validation-using-javascript.html

Anonymous said...

thanks appreciate it

Anonymous said...

clear to understand....

Anonymous said...

anyone knows how to validate numbers in calculator only 10numbers using css/javascript

Unknown said...
This comment has been removed by the author.
Anonymous said...

It so nice.. Thanks a lot!

Anonymous said...

Works perfectly! Great job! Thanks!

Anonymous said...

nice very helpful

Unknown said...

its very clear

Anonymous said...

thanks appreciate it

Anonymous said...

Its really helpful for the beginners.......

Anonymous said...

That's powerful!!!

Unknown said...

Ở giai đoạn tuổi 20 - Bảo vệ và hồi phục làn da
Ở độ tuổi này, làn da của bạn rất dễ bị tổn thương bởi những chế độ ăn uống không lành mạnh và môi trường làm việc ngoài trời của bạn. Collagen shiseido từ Nhật dạng nước Chính những thương tổn này sẽ kích thích quá trình lão hóa làn da mà bạn có thể không nhận ra rõ ràng.
Những dấu hiệu lão hóa da để bạn nhận biết đó là: xuất hiện quầng thâm ở mắt, vien uong collagen cua nhat ban mắt hay bị sưng và gương mặt hốc hác, mệt mỏi. Trong trường hợp này, tốt nhất các cô nàng nên sử dụng kính râm và thoa kem chống nắng mỗi khi ra ngoài. Hơn nữa, cách bổ sung collagen cho dabí quyết thật đơn giản mà hiệu quả mình mong rằng bài chia sẻ này sẽ giúp ích được các bạn rất nhiều. hàng ngày. bạn nên sử dụng kem dưỡng ẩm có chỉ số SPF tối thiểu là 30. Bí quyết này sẽ giúp bạn kích thích quá trình chống oxy hóa và cải thiện làn da "sống mãi với thời gian" của mình.
Ở giai đoạn tuổi 30 - Cải thiện làn da
Cảm thấy chán nản
Dấu hiệu này có thể do nhiều nguyên nhân. Tuy nhiên, thành phần dinh dưỡng của tấm gạo các nghiên cứu đã chứng minh thiếu dưỡng chất cũng có thể gây chán nản, cụ thể là axit béo omega-3, amino axit và một số vitamin cũng như khoáng chất khác.
Rụng tóc
Thiếu vitamin B6 có thể gây ra rụng tóc,thành phần dinh dưỡng của chuối sứ nhưng đó cũng là dấu hiệu cho thấy cơ thể bạn cần bổ sung kẽm. Nếu tóc còn bị khô và dễ gãy, đó là vì thiếu vitamin A. Vì vậy nếu tóc rụng một vài sợi, gia tri dinh duong cua hat dieu đó chỉ là dấu hiệu bình thường; nhưng nếu quá nhiều, nguyên nhân có thể liên quan đến vấn đề dinh dưỡng.

JannethManalu said...
This comment has been removed by the author.
jasa website gembling said...

Agen BandarQQ Situs DominoQQ Poker QQ Online BandarQ288

BandarQ288 merupakan agen bandarqq online, pokerqq, dominoqq dan situs qq terbaik pilihan para professional di indonesia pada saat ini, dan kebetulan merupakan salah satu situs bandarq poker qq online yang ternama dan terbesar. BandarQ288 juga memiliki tampilan dan design halaman utama yang memanjakan mata. Bagi para bettor, bisa menikmati semua taruhan kartu yang tersedia di situs kami tanpa ribet. Kualitas server terbaik sudah dihadirkan untuk para calon pemain dan memiliki sertifikasi gambling international di negara singapura. Untuk saat ini server yang kami pergunakan adalah pkv games atau pokerv, server ini dipilih karena memang mempunyai performa dan kualitas yang sangat baik. Selain itu pihak BandarQ288 juga melakukan upgrade server setiap tahunnya, demi menampung ribuan player online yang setiap hari makin bertambah. Hal ini pun menjadi salah satu kewajiban, agar setiap member mendapatkan keamanan dan kenyamanan dalam bermain.
agen bola

Poker online
Poker Uang Asli


Prediksi Bola
Jadwal Bola
Agen Bola



dominoqq
bandarqq
poker qq online
pkv games