Monday, 12 August 2013

PreSaveAction for Sharepoint Form Fields Validations

HI All,

 Today I will share you one very useful in-built JavaScript functionality, which is used for validating the form fields. Obviously u can go for “Calculated columns”, “Column Validations”, “List Validations” for some validations and required result.

But,,,,,,, Sometimes, the requirement could be quite complicated..

Eg :
#“Start Date” less than “End Date”
##Out of two fields, if one is filled then save the item else cancel.
Likewise this can be used for many validations which we cannot do OOTB.

Ok, now I will give the basic code,
if the requirement is “End date” should not be earlier than “Start Date”..

========================================================================
<script language=”javascript” type=”text/javascript”>
function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Start Date”);
var date2 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”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
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == “” || tempString.indexOf(identifier) == tempString.length – len)) {
return tags[i];
}
}
return null;
}
</script>
========================================================================

U can just do some simple tweaks in this piece of code and can do magicsss :)
See you next time… byyyeee..:)

No comments:

Post a Comment