Validate a SharePoint Date Field against Current Date in Javascript
Consider the following scenario:
- You have a SharePoint Site which has its regional settings set to English (UK) - so that the date format becomes dd/mm/yyyy in all date pickers
- You would like to validate a particular date field in your List or Document Library against the current date
- If the validation does not pass, you should not allow the form to save
So what the script does is:
- Uses the sputility (check my previous posts and also look at http://sputility.codeplex.com) to get the particular SharePoint date field
- It comes out as a date datatype, so I cast it to string
- Since the format is in dd/mm/yyyy and Javascript compare and date functions work only with mm/dd/yyyy, I am converting them back to that format
- then using UTC string conversions and comparing...
Enjoy!
<script type="text/javascript">
function PreSaveAction() {
var createdate = SPUtility.GetSPField('Date of Creation').GetValue();
var createdatestr=createdate.toString();
var dt1 = createdatestr.substring(0,2);
var mon1 = createdatestr.substring(3,5);
var yr1 = createdatestr.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
var dtCr = new Date(temp1);
var CreatedDateInUTC = dtCr.toUTCString();
var currentTime = new Date();
var CurDateInUTC = currentTime.toUTCString();
var dt3 = new Date(CreatedDateInUTC);
var dt4 = new Date(CurDateInUTC);
if(dt3 > dt4){
alert('Date of Creation cannot be greater than Current Date!');
return false;
}
return true;
} </script>
Thanks! . it helped a lot.
ReplyDelete