Friday, January 22, 2010

Javascript Radio Button validation with function

Function to check a radio button if checked or not
function chkRadio(radio)
{
 var i, flg=0;
 
 for(i=0; i<radio.length; i++)
 {
  if(radio[i].checked)
   flg=1;
 }
 
 return flg;
}

Usage:
if(!chkRadio(document.myForm.group1))
{
 alert("Please select");
 return false;
}
.
.
<form name="myForm" .....
.
<input type="radio" value="V1" name="group1">
<input type="radio" value="V2" name="group1">
<input type="radio" value="V3" name="group1">

Thursday, November 26, 2009

Javascript Date Validation / Comparison

Problem:
User enters two dates, say start date and end date, then we need to alert him if the start date is greater than end date.

Solution:
Assume we are getting the date to the input field using a datepicker.

First we have to convert the string into Date() object using
var dObj = new Date(year, month, date); (also note: the month value range from 0 to 11)
and we can compare the dates.

Example:
var x = document.formName;

//assume the date format is YYYY/MM/DD
var sDate1 = x.start_date.value;
var sDate = new Date(sDate1.split('/')[0], parseInt((sDate1.split('/')[1])-1), sDate1.split('/')[2]);
var eDate1 = x.end_date.value;
var eDate = new Date(eDate1.split('/')[0], parseInt((eDate1.split('/')[1])-1), eDate1.split('/')[2]);
if(eDate >= sDate)
{
    alert("End date is greater than start date; please try again....");
    return false;
}

-