Sunday, December 27, 2009

Date validation using JavaScript


How to validate date in JavaScript?




Following example shows you how to validate date in JavaScript as a client side validation.





In some cases you may want to validate date and time in your web applications. In such cases you can use javascript to validate date and time. In here this JavaScript checks the user input is in valid date format. It checks DD-MM-YYYY date format and MM-DD-YYYY date formats. First you have to select a date format. Then enter date in given text box and press validate button. If your input date is in correct format the JavaScript tells you that the input date is in correct format. Otherwise it gives an error message telling you that your input date is not in the correct format.





Demo- Validate Date using JavaScript.


JavaScript Date Validator



Select date format

view code



Enter Date



(*Use "-" or "/" as date separator. eg. 07-11-2009 of 12/12/2009)




Try it!




Bookmark and Share




1. Example code for validate date using JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function dateValidate(){

var inputDate = document.getElementById("txtDateValidate").value;

var dateFormat = document.getElementById("selectDateFormat").value;

var dateValidateRegExp1 = /^\d{2}\/\d{2}\/\d{4}$/;

var dateValidateRegExp2 = /^\d{2}-\d{2}-\d{4}$/;

var dateSplitterIndex = 0;

var isValidDate = 0;

var dateErrorMessage = "Invalid date format.\nDate format should be "+

(dateFormat==1?"MM-DD-YYYY":"DD-MM-YYYY")+

"\nPlease correct and submit again.";


isValidDate+=match_count(inputDate,dateValidateRegExp1);
if(isValidDate>0){

dateSplitterIndex=0;

}else{

isValidDate+=match_count(inputDate,dateValidateRegExp2);

if(isValidDate>0){

dateSplitterIndex=1;

}

}


if(isValidDate==0){

alert(dateErrorMessage);

return false;

}

var dateSplitter="-";

var dateSplitters=Array("/","-");

var monthNames=Array("January","February","March","April",

"May","June","July","August","September",

"October","November","December");
var dmy = inputDate.split(dateSplitters[dateSplitterIndex]);

var month,day,year = 0;

//MM-DD-YYYY DD-MM-YYYY



switch(parseInt(dateFormat)){

case 1:{

month= dmy[0];

day = dmy[1];

year = dmy[2];

}break;



case 2:{

month= dmy[1];

day = dmy[0];

year = dmy[2];

}break;



}
if(month>=1 && month<=12){

if(!(day>=1 && day<=31)){

alert("Please enter valid date (1-31)");

return false;

}

}else{

alert("Month should be 1-12 "+month +" is invalid");

return false;

}



if(year%4==0){

if(month==2){

if(day>29){

alert("February can't have more than 28 days except in a leap year");

return false;

}

}else{

if(!checkDaysOfTheMonth(month,day)){

alert(monthNames[month-1]+" can't have "+day+" days");

return false;

}

}

}else{

if(month==2){

if(!checkDaysOfTheMonth(month,day)){

alert(monthNames[month-1]+" can't have "+day+" days");

return false;

}

}else{

if(!checkDaysOfTheMonth(month,day)){

alert(monthNames[month-1]+" can't have "+day+" days");

return false;

}

}

}
alert("Date you have entered is valid!");

return true;

}

/*--------------------------------------------------------*/

function checkDaysOfTheMonth(month,day){
var daysOfMonth = Array();

daysOfMonth[0] = Array(1,31);

daysOfMonth[1] = Array(2,28);

daysOfMonth[2] = Array(3,31);

daysOfMonth[3] = Array(4,30);

daysOfMonth[4] = Array(5,31);

daysOfMonth[5] = Array(6,30);

daysOfMonth[6] = Array(7,31);

daysOfMonth[7] = Array(8,31);

daysOfMonth[8] = Array(9,30);

daysOfMonth[9] = Array(10,31);

daysOfMonth[10] = Array(11,30);

daysOfMonth[11] = Array(12,31);



for(var i=0;i<daysOfMonth.length;i++){

if(i==(month-1)){

if(!((day>=1) && (day<=daysOfMonth[i][1]))){

return false;

}else{

return true;

}

}

}

}
/*--------------------------------------------------------*/

function match_count(str,regEx){

if(regEx.test(str)){

return 1;

}else{

return 0;

}

}
-->

</script>
Html Code


<html>

 <head>

  <title>How to validate date using JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td align="right"> Select date format </td>

<td align="left">

<select name="selectDateFormat" id="selectDateFormat">

<option value="1">MM-DD-YYYY</option>

<option value="2">DD-MM-YYYY</option>

</select>

</td>

<td align="left"> </td>

</tr>

<tr>

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

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

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

</tr>

<tr>

<td align="right" valign="top">Enter Date </td>

<td align="left">



<input name="txtDateValidate" type="text" id="txtDateValidate" />

</td>

<td align="left">

<input name="btnDateValidation" type="submit" id="btnDateValidation" value="Validate" onclick="javascript:dateValidate();" />

</td>

</tr>

</table>

</body>

</html>


 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript

©-Copyright By Duminda Chamara
JavaScript Validation  

Sunday, December 13, 2009

JavaScript validation

Need more help on JavaScript validation?

 Today javascript plays a major role in web applications. Using javascript in your web sites/ web applications you can gain much user attraction to your web site. Before submitting a form you have to think what kind of data will be entered into your form. So no doubt you have to validate user inputs before submitting the form. It saves web-server's band width and user's valuable time. Therefore it is a good practice to validate user inputs using javascript as a client-side validation. Follow links bellow to learn basic javascript validation you need frequently.

Bookmark and Share




String functions in JavaScript


Most common string functions in JavaScript




Sometimes you need to deal with strings in javascript. It will be getting a length of a string or determine the character position in a string.




How to get a length of a string in java script?


Use the length method to find out how many characters in string. It returns the total characters in the string.

How Change the case of a string?


You can change the case of a string to lowercase or to upper case using javascript function.
To change a string to lowercase use toLowerCase() function and make uppercase use toUpperCase() function.

How to get the index of a character?


You can get the index of the first occurrence of a specified character using indexOf() function.
This returns -1 if the character not present in the given string, otherwise it returns the index of the first occurrence. The index starts from zero. There is an another method called lastIndexOf() to get the index of a specified character. It start checking right to left.

How create sub string in javascript?


Use substr() function to make sub strings in javascript. This method returns specified parts of the string. You have to
specify the starting position of the string and then how many characters do you want to extract from the string. Take into mind first character is 0. If ending position is greater than the total length of the string it returns the whole input string as result. Use substring() function to get all characters between starting and ending positions.





Demo- String functions in JavaScript.
1. Get string length using JavaScript.
Enter string to get length


view code

2.Change text case using JavaScript.
Enter string to change the case



view code




3.Get the index of a character using JavaScript.




 Enter a character



Type your text


view code

4.Make sub strings using JavaScript.

Enter a string to make sub string



Starting position



 Enter ending position


view code



Bookmark and Share




1. Example code for get string length using JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function getStringLength(str){

if(str==''){

alert("Please enter a string");

}else{

alert(str.length+" characters in the string");

}

return true;

}

-->

</script>
Html Code


<html>

 <head>

  <title>Get string length in JavaScript </title>

 </head>

<body>

 <input type="text" id="stringLength" name="stringLength" />
<input name="getStringLength" type="button" onClick="javascript:getStringLength(this.value);" value="Get Length" />

</body>

</html>

2. Sample code for change text case in JavaScript.

JavaScript code
<script type="text/javascript" language="javascript">

<!--

function changeCase(textCase){

var text=document.getElementById("txtUpperorLower").value;

if(text==''){

alert("Please enter a string");

return false;

}

switch(textCase){

case 1:{

alert(text.toUpperCase());

}break;

case 2:{

alert(text.toLowerCase());

}break;

}

return true;

}
-->

</script>

<html>

 <head>

  <title>Chanage text case in JavaScript </title>

 </head>

<body>

 <input type="text" name="txtUpperorLower" id="txtUpperorLower" value="" />

<input name="setUpperCase" id="setUpperCase" type="button" onClick="javascript:changeCase(1);" value="To Upper" /> <input name="setLowerCase" id="setLowerCase" type="button" onClick="javascript:changeCase(2);" value="To Lower" />

</body>

</html>

3. Sample code for get character index in JavaScript.

JavaScript code
<script type="text/javascript" language="javascript">

<!--

function getIndex(){

var text=document.getElementById("txtGetIndex").value;

var textChar=document.getElementById("txtCharacter").value;

if(text==''){

alert("Please enter a string");

return false;

}else if(textChar==''){

alert("Please enter a character");

return false;

}else if(textChar.length>1){

alert("Please enter a single character");

return false;

}

var index=text.indexOf(textChar)

if(index<0){

alert("Character not found");

}else{

alert("Index of "+textChar+" is "+index);

}

return true;

} -->


</script><html>

 <head>

  <title>Get character index in JavaScript </title>

 </head>

<body>

 Enter a character <input type="text" name="txtCharacter" id="txtCharacter" value="" size="5" /> Type your text

<input type="text" name="txtGetIndex" id="txtGetIndex" value="" />

<input name="setCharacterIndex" id="setCharacterIndex" type="button" onClick="javascript:getIndex();" value="Get Index" />

</body>

</html>

4. Sample code for making sub string using JavaScript.

JavaScript code
<script type="text/javascript" language="javascript">

<!--

function getSubstring(){

var start=document.getElementById("txtStart").value;

var end =document.getElementById("txtEnd").value;

var text=document.getElementById("txtToSubstring").value;

if(isNaN(start)){

alert("Please enter a valid start value");

return false;

}else if(isNaN(end)){

alert("Please enter a valid ending value");

return false;

}else if(start<0 || end<0 || end==0){

alert("Please enter a valid start and ending value");

return false;

}else if(text==''){

alert("Please enter a string to make substring");

return false;

}



alert(text.substr(start,end));

return true;

}-->


</script><html>

 <head>

  <title>Make substring in JavaScript </title>

 </head>

<body>

Enter a string to make substring <input type="text" name="txtToSubstring" id="txtToSubstring" value="Hello World" /><br />

Starting position <input type="text" name="txtStart" id="txtStart" value="0" size="5" /><br />

Enter ending position <input type="text" name="txtEnd" id="txtEnd" value="2" size="5" />

<input name="getSubstring" id="getSubstring" type="button" onClick="javascript:getSubstring();" value="Make Substring" />

</body>

</html>


 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript

©-Copyright By Duminda Chamara
JavaScript Validation  

Sunday, December 6, 2009

Validate Multiple-Select List Box


How to validate Multiple-Select List Box Using JavaScript?




Following example shows you to validate Multiple Select List Box in javascript as a client side validation.





Multiple-Select List Boxes allow the user to select more than one list item per time. It returns an array of values when user pressed submit button. The return result containing an array of values. You can run this values in a for loop and check what are the selected items. If there is no selected item in the list box this script prompt the user to select a value. User should select at least one item in the list box. Sometimes you may want to select at least one item from the Multiple-Select List Box and not more than x items (x=any possible value). In this example you can check above requirement. Using this JavaScript you can get total items in the Multiple-Select List Box, Selected Items of the Multiple-Select List Box also.
Following examples show you how to validate a Multiple Select List Box in Javascript.

 






Demo- Validate Multiple Select List Box In JavaScript


Multiple-Select List Box Validation
Select a day and press validate button.


1. Ask user to select at least one item

  From the List Box.

view code
 


2.Get the number of items in the Multiple-Select List Box

view code



3.Get all selected items in the Multiple-Select List Box

view code



4.Select at least one item, but not more than

  three(x number of items) items from the

  Multiple –Select List Box

view code




Try it!





Bookmark and Share





1. Example code for select at least one item from the List Box in JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function validateListBox(){

var list=document.getElementById("multipleListBox");

var selected_items=0;

for(var i=0;i<list.length;i++){

if(list[i].selected){

selected_items++;

}

}

if(!(selected_items>0)){

alert("Please select at least one item");

return false;

}else{

alert("Ok\nYou have sleeted item(s) from list box");

return false;

}

}



-->

</script>
Html Code


<html>

 <head>

  <title>How to Validate Multiple Select List Box </title>

 </head>

<body>

<table border="0">

<tr>

<td>Select a day and press validate button.</td>

<td align="left"><select name="multipleListBox" size="4" multiple="multiple" id="multipleListBox">

<option value="Sunday">Sunday</option>

<option value="Monday">Monday</option>

<option value="Tuesday">Tuesday</option>

<option value="Wednesday">Wednesday</option>

<option value="Thursday">Thursday</option>

<option value="Friday">Friday</option>

<option value="Saturday">Saturday</option>

</select></td>

</tr>

<tr>

<td>1. Ask user to select at least one item <br />

&nbsp;&nbsp;From the List Box. </td>

<td align="left"><input name="validateMultipleListBox1" type="submit" id="validateMultipleListBox1" value="Validate" onclick="javascript:validateListBox();" /></td>

</tr>

</table>

</body>

</html>

2. Get the number of items in the multiple select List-Box using JavaScript.

<script type="text/javascript" language="javascript">

<!--
function getTotalListBoxItems(){

var list=document.getElementById("multipleListBox");

alert("No of items in the list box = "+list.length);

return true;

}

</script>
Html Code
<html>

 <head>

  <title>How to get total item of a multiple select list-box in JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td>Select a day and press validate button.</td>

<td align="left"><select name="multipleListBox" size="4" multiple="multiple" id="multipleListBox">

<option value="Sunday">Sunday</option>

<option value="Monday">Monday</option>

<option value="Tuesday">Tuesday</option>

<option value="Wednesday">Wednesday</option>

<option value="Thursday">Thursday</option>

<option value="Friday">Friday</option>

<option value="Saturday">Saturday</option>

</select></td>

</tr>

<tr>

<td>2.Get the number of items in the Multiple-Select List Box</td>

<td align="left"><input name="validateMultipleListBox2" type="submit" id="validateMultipleListBox2" value="Validate" onclick="javascript:getTotalListBoxItems();" /></td>

</tr>

</table>

</body>

</html>

3. Get all selected items in the multiple select List-Box using JavaScript.

<script type="text/javascript" language="javascript">

<!--
function getSelectedValuesOfTheListBox(){

var list=document.getElementById("multipleListBox");

var selectd_items="";

for(i=0;i<list.length;i++){

if(list[i].selected){

selectd_items+=list[i].value+"\n";

}

}

if(selectd_items!=""){

alert("Selected items are\n"+selectd_items);

}else{

alert("There are no selected items in the multiple select list box");

}

}
-->

</script>
Html Code
<html>

 <head>

  <title>How to get selected items in a multiple select list box in JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td>Select a day and press validate button.</td>

<td align="left"><select name="multipleListBox" size="4" multiple="multiple" id="multipleListBox">

<option value="Sunday">Sunday</option>

<option value="Monday">Monday</option>

<option value="Tuesday">Tuesday</option>

<option value="Wednesday">Wednesday</option>

<option value="Thursday">Thursday</option>

<option value="Friday">Friday</option>

<option value="Saturday">Saturday</option>

</select></td>

</tr>

<tr>

<td>3.Get all selected items in the Multiple-Select List Box</td>

<td align="left"><input name="validateMultipleListBox3" type="submit" id="validateMultipleListBox3" value="Validate" onclick="javascript:getSelectedValuesOfTheListBox();"/></td>

</tr>

</table>

</body>

</html>

4. Select items with a condition in the multiple select List-Box using JavaScript.

<script type="text/javascript" language="javascript">

<!--
function SelectItemsWithCondition(){

var list=document.getElementById("multipleListBox");

var selectd_items=0;

for(i=0;i<list.length;i++){

if(list[i].selected){

selectd_items++;

}

}

if(selectd_items==0){

alert("Please select at least one item");

}else if(selectd_items>3){

alert("Don't select more than three items");

}

}
-->

</script>
Html Code
<html>

 <head>

  <title>How to validate multiple select list-box in JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td>Select a day and press validate button.</td>

<td align="left"><select name="multipleListBox" size="4" multiple="multiple" id="multipleListBox">

<option value="Sunday">Sunday</option>

<option value="Monday">Monday</option>

<option value="Tuesday">Tuesday</option>

<option value="Wednesday">Wednesday</option>

<option value="Thursday">Thursday</option>

<option value="Friday">Friday</option>

<option value="Saturday">Saturday</option>

</select></td>

</tr>

<tr>

<td>4.Select at least one item, but not more than<br />

&nbsp;&nbsp;three(x number of items) items from the <br />&nbsp;&nbsp;Multiple –Select List Box</td>

<td align="left"><input name="validateMultipleListBox4" type="submit" id="validateMultipleListBox4" value="Validate" onclick="javascript:SelectItemsWithCondition();" /></td>

</tr>

</table>

</body>

</html>





Useful JavaScript Validations

©-Copyright By Duminda Chamara
JavaScript Validation  

Sunday, November 29, 2009

Get screen resolution in JavaScript

How to get screen resolution in JavaScript?


 You can get your screen resolution/ screen width and height using following JavaScript. It shows you the screen resolution of your computer screen in pixel. When designing web application for different screen sizes this may be very useful.


HTML and JavaScript Code
<head>
<title>Screen Resolution</title>
<script type="text/javascript" language="javascript">
function getScreenResolution(){
                var width=screen.width;
                var height = screen.height;
                document.getElementById("txt_screen_width").value=width;
                document.getElementById("txt_screen_height").value=height;
}
</script>
</head>
<body onLoad="javascript:getScreenResolution();">
<form id="form_screen_resolution" name="form_screen_resolution" method="post" action="">
  <table width="200" border="0">
    <tr>
      <td colspan="2" align="center"><strong>Screen resolution </strong></td>
    </tr>
    <tr>
      <td>Width</td>
      <td valign="middle">
        <input name="txt_screen_width" type="text" id="txt_screen_width" size="5" />
        px      </td>
    </tr>
    <tr>
      <td>Height</td>
      <td valign="middle">
        <input name="txt_screen_height" type="text" id="txt_screen_height" size="5" />
        px      </td>
    </tr>
  </table>
</form>
</body>
</html>

Limit characters in textarea

How to limit the number of characters entered in a text box or text aria in JavaScript?

Following example shows you how to limit characters in a text area in javascript as a client side validation.


In some cases you may want to limit number of input characters in a text box or text aria. In such situation you can use a very simple JavaScript to do it. In HTML there is no way to limit the input characters in a text box or text area. Using following JavaScript you can limit the input character length as client-side validation. This JavaScript works on onkeyup event of the text box / text area. When user entered a character from the keyboard it counts the total length of the text you have entered. It shows a message when you are tried to enter a single character more than the character length you defined.




Demo- Limit characters in a text area using JavaScript.
JavaScript Character Counter
1.Enter description (50 characters only).
Characters remaining view code
2.Limit characters in a text area.
Enter number of characters you want to limit.
Enter your text here
Characters remaining view code


Try it!
Bookmark and Share

1. Example code for limit number of input characters in a text area using JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript"> <!-- function limitInputCharacters(inputText,limit){ var text=inputText; if(text.length>limit){ alert("You have entered more than "+limit+" characters!"); document.getElementById("txtLimitCharacters").value=text.substr(0,limit); return false; } document.getElementById("charactersRemaining").value=(limit-text.length); return true; } --> </script>
Html Code
<html> <head> <title>How to Limit Characters in a Text Area </title> </head> <body> <table border="0"> <tr> <td valign="top"> 1.Enter description (50 characters only). </td> <td align="left"> <textarea name="txtLimitCharacters" cols="40" rows="8" id="txtLimitCharacters" onkeyup="javascript:limitInputCharacters(this.value,50);" ></textarea> </td> <td align="left">&nbsp;</td> </tr> <tr> <td align="right">Characters remaining </td> <td align="left" > <input name="charactersRemaining" type="text" id="charactersRemaining" disabled="disabled" size="5" /> </td> <td align="left"> </td> </tr> </table> </body> </html>

2. Limit user input text using JavaScript.

<script type="text/javascript" language="javascript"> <!--
function limitCharacters(inputText){ var text=inputText; var characterLimit=document.getElementById("numberOfCharacters").value; if(!isNaN(characterLimit)&& parseInt(characterLimit)>0){ if(text.length>characterLimit){ alert("You are only allowed to enter maximum "+parseInt(characterLimit)+" characters only"); document.getElementById("javaScriptCharacterCounter").value=text.substr(0,characterLimit); return false; }else{ document.getElementById("charactersRemaining2").value=(characterLimit-text.length); } }else{ alert("Please enter valid integer value for\nCharacter limit"); document.getElementById("numberOfCharacters").value="50"; document.getElementById("javaScriptCharacterCounter").value=""; document.getElementById("numberOfCharacters").focus(); return false; } } </script>
Html Code
<html> <head> <title>How to limit user input text in text area </title> </head> <body> <table border="0"> <tr> <td align="right">Enter number of characters you want to limit. </td> <td align="left" ><input name="numberOfCharacters" type="text" id="numberOfCharacters" value="50" size="5" /></td> <td align="left">&nbsp;</td> </tr> <tr> <td align="right">Enter your text here </td> <td align="left" ><textarea name="javaScriptCharacterCounter" cols="40" rows="8" id="javaScriptCharacterCounter" onkeyup="javascript:limitCharacters(this.value);" ></textarea></td> <td align="left">&nbsp;</td> </tr> <tr> <td align="right">Characters remaining </td> <td align="left" ><input name="charactersRemaining2" type="text" id="charactersRemaining2" disabled="disabled" size="5" /></td> <td align="left"> </td> </tr> </table> </body> </html>
» How to get screen resolution in JavaScript
» How to limit characters in textarea using JavaScript
» How to validate decimal number in JavaScript
» How to validate an email address in JavaScript
» How to validate date using JavaScript
» JavaScript String functions
» How to validate multiple select list box in JavaScript
» How to generate random numbers in JavaScript
» How to validate multiple check box in JavaScript
» How to validate user login in JavaScript
» How to validate drop down list in JavaScript
» How to validate radio button group in JavaScript
» How to create JavaScript alerts
» How to create popup windows in JavaScript
» How to count words in a text area using JavaScript
©-Copyright By Duminda Chamara JavaScript Validation

Sunday, November 22, 2009

Validate Decimal Number


How to validate decimal number using JavaScript?




Following example shows you to validate a decimal number in javascript as a client side validation




In some situations you may want to validate a decimal number before submitting your form. It is good practice to validate input data before they sent to the web server. Using a simple javascript you can validate a decimal number. A decimal number contains 0 to 9 integer values and only one decimal point. There is an in-built function isNaN() that can use to validate a decimal number in javascript.
Using following javascript you can check
whether a particular number is a valid decimal number of not.


Demo- Validate Decimal Number In JavaScript
1. Validate decimal number.
Enter a Decimal Number




view code



2. How to validate a decimal number on key press event.



Enter a number

view code



3. Use following code to validate a decimal number with specified decimal places.



Number of Decimal Points

view code
Enter Decimal Number







Enter a value and click on submit button to test whether input is a valid decimal number or not. If you enter an invalid decimal number JavaScript alerts you, you have entered an invalid number. Otherwise it alerts the input is a valid decimal number.







Bookmark and Share


1. Example code for validate a decimal number in JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function validateDecimalNumber(){

var value = document.getElementById("textDecimalNumber").value;

var message = "Please enter a decimal value";

if(value!=""){

if(isNaN(value)==true){

alert(message);

return false;

}else{

alert(value+" is a valid decimal number");

return true;

}

}else{

alert(message);

return false;

}

return false;

}

-->

</script>
Html Code


<html>

 <head>

  <title>How to Validate Decimal Number in JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td>Enter Decimal Number </td>

<td>

<input name="textDecimalNumber" type="text" id="textDecimalNumber" />

</td>

</tr>

<tr>

<td>&nbsp;</td>

<td>

<input name="btnDecimalNumberValidator" type="submit" id="btnDecimalNumberValidator" onclick="javascript:validateDecimalNumber();" value="Validate" />

</td>

</tr>

</table>

</body>

</html>

2. Example code for validate a decimal number on key press event in JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function validate(){

var value = document.getElementById("txtDecimal").value;

var message = "Please enter a decimal value";

if(isNaN(value)==true){

alert(message);

document.getElementById("txtDecimal").select();

return false;

}else{

return true;

}

}

-->

</script>
Html Code


<html>

 <head>

  <title>How to Validate Decimal Number in KeyPress Event in JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td>Enter Decimal Number </td>

<td>

<input name="textDecimalNumber" type="text" id="textDecimalNumber" />

</td>

</tr>

<tr>

<td>&nbsp;</td>

<td>

<input name="txtDecimal" type="text" id="txtDecimal" onkeyup="javascript:validate();" />

</td>

</tr>

</table>

</body>

</html>

3. Custom Decimal number validation using JavaScript.

<script type="text/javascript" language="javascript">

<!--
//------------------------------------------------------------------

function showDecimalPointError(){

var message="Please enter an integer value";

alert(message);

document.getElementById("textDecimalPoints").value="2";

return false;

}

//------------------------------------------------------------------

function CheckDecimalPoints(){

var decimalPoints=document.getElementById("textDecimalPoints").value;



for(var x=0;x<decimalPoints.length;x++){

if(decimalPoints.charAt(x)=="."){

showDecimalPointError();

}

if(isNaN(decimalPoints.charAt(x))){

showDecimalPointError();

}

}

return true;

}

//------------------------------------------------------------------

function customValidation(){

var preferredDecimalPoints=document.getElementById("textDecimalPoints").value;

var decimalPointCount=0;

var decimalNumber = document.getElementById("txtCustomValidation").value;

var pointFound=false;

var decimalPlaces=0;



for(var i=0;i< decimalNumber.length ;i++){

var _char=decimalNumber.charAt(i);



if(pointFound==true){

decimalPlaces++;

}

if(_char=="."){

pointFound=true;

decimalPointCount++;

if(decimalPointCount>1){

break;

}

}else if(isNaN(_char)){

setError()

return false;

}

}

if(decimalPointCount!=1){

setError()

return false;

}else if(decimalPlaces!=preferredDecimalPoints){

setError()

return false;

}else if(isNaN(decimalNumber)){

setError()

}else{

alert(decimalNumber+" is a valid decimal number");

}

return true;

}

//------------------------------------------------------------------

function setError(){

var message="Please enter a valid decimal number";

alert(message);

document.getElementById("txtCustomValidation").select();

document.getElementById("txtCustomValidation").focus();

return false;

}

//-------------------------------------------------------------------->

</script>
Html Code
<html>

 <head>

  <title>How to Validate Decimal Number in JavaScript </title>

 </head>

<body>
<table border="0">

<tr>

<td>Number of Decimal Points </td>

<td><label>

<input name="textDecimalPoints" type="text" id="textDecimalPoints" size="5" value="2" onkeyup="javascript:CheckDecimalPoints();" " />

</label></td>

</tr>

<tr>

<td>Enter Decimal Number </td>

<td><label>

<input name="txtCustomValidation" type="text" id="txtCustomValidation" />

</label></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><label>

<input name="btnCustomValidation" type="submit" id="btnCustomValidation" value="Validate" onclick="javascript:customValidation();" />

</label></td>

</tr>

</table></body>

</html>


 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript

©-Copyright By Duminda Chamara
JavaScript Validation