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