Friday, October 17, 2008

Validating Date field in SharePoint through Javascript

Just put the following code in NewItem.aspx :

function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Contract Date");

var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Contract End Date");

var arrDate1 = date1.value.split("/");

var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);

var arrDate2 = date2.value.split("/");

var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);

if(useDate1 > useDate2)
{
alert("The end date cannot happen earlier than the start date");

return false; // Cancel the item save process
}

return true; // OK to proceed with the save item }