Add JavaScript Date Validation into List Item forms
October 10, 2007
Another undocumented piece of SharePoint.
I want to validate two fields on a new list item form by invoking JavaScript custom function. They are two date fields and I want to ensure that the end date can't happen before the start date. My first idea was to attach a validation function on the onclick event of the Submit button.
I started by inspecting the generated HTML of the form. The Submit button already has a onclick() code which is:
if (**!PreSaveItem()\_**) return false;WebForm\_DoPostBackWithOptions(new WebForm\_PostBackOptions("ctl00$ctl13$g\_740c1963\_b0da\_4b45\_9b71\_0dcca5d082b0$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true))
Searching in the SharePoint JavaScript files in the LAYOUT folder, I found the definition of PreSaveItem function in FORMS.JS file. It simply invokes PreSaveAction function, if defined.
Finally, it was just a matter of inserting a custom function named PreSaveAction in a <SCRIPT> block of the NewForm.aspx (and EditForm.aspx). I also used the date parse code from this forum.
The code I put in NewItem.aspx is like this (note that I use getTagFromIdentifierAndTItle function from my older blog entry):
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
}