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
}
great post Res, i had this exact issue albeit for different field types but i can modify your code. cool cheers for this, will be sure to give you props – unfortunately its on an intranet
hi me again,
I am trying to validate on empty fields – they want javascript validation not just serverside .net, any idea what a single line of text would be identified as in your javascript getTagFromIdentifierAndTitle? e.g. “INPUT”, “”, “fieldname” my code is
var stringExplain = getTagFromIdentifierAndTitle(“INPUT”,”string”,”explain”);
if (stringExplain.value.length==0)||(explain.value==null)
{
alert(“please enter a explanation”);
return false;
}
return true;
but i have a feeling string is not the answer?
I couldn’t work out it for me, actually i got lost in which Newform.aspx i have to add code.
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions12TEMPLATESiteTemplates
under various sub dir of this dir i found 12 NewForm.aspx files.
Can you please suggest on this?
Hi, great post, thanks.
Have you got any suggestion to validate a user and group field?
Hi Can you help in more detailed. I can’t find any script blok on the newforms.aspx
I am using wss 3.0 sp1
This could also be done with an item event handler attached to the list. If you’re able to customize your site with custom features, do a Google search for the ItemAdding event and you can whip one up pretty quickly.
Here’s some code to chew on:
http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3119964&SiteID=17&mode=1
To pramod and murali kanaan:
You have to use SharePoint Designer in order to add JavaScript code to the list maintenance ASPX pages.
To justin:
An EventHandler won’t do because it’s a server-side component, not client-side.
To bfalchi:
I’m also investigating it. I will share my discoveries, don’t worry.
How can I know the field names of the html fields? And where should I have to add this function in the NewForm.aspx or EditForm.aspx? Please help me. Its really very helpfull for me.
Hi, kalyan93
You can put this code either in NewForm.aspx or in EditForm.aspx, in a SCRIPT tag that you create, editing the ASPX files from SharePoint Designer.
The HTML fields codes you are referring to are just the field names that SharePoint uses (such as “Contract Date”). The second parameter in the function is field type, you can find more information about that in this blog post.
I hope it helps.
Hi I got the information that how to get the field name. I think it would be helpfull for some other.
Go to List / Document Library Settings, click on the name of the column to modify it and in URL find the last parameter value.
May be usefull.
@Edin
getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Contract Date”); is this function already existing in the sharepoint code or we need to write the definition of that function as you gave in your older blog entry. Because when I m trying to use this in my newForm.aspx page it is throughing an error like “object expected” at that corresponding line. Please help me….
Hi kalyan93,
this function is not provided by SharePoint, so you must copy-paste it to the ASPX markup code or reference an external JS file from the ASPX.
I added this “getTagFromIdentifierAndTitle(tagName, identifier, title) ” also in the Newform.aspx, but after adding this control is not going to the “PreSaveAction ” function. I dont know where it is goint.. no single alert is working in both the functions.. any clue??
Kalyan93, can’t help you much without seeing the code, but please double-check that you have correctly copied both of the functions (PreSaveAction and GetTagFromIdentifierAndTitle).
Any progress?
Edin
Hi Your post is really helpfull for me. There is a syntax error in the function “getTagFromIdentifierAndTitle” unclosed for loop. Because of that only the error is coming. Thanks a lot Edin.
Thanks
Kalyan
You’re welcome! I’m glad I’ve been helpful, that’s the purpose of sharing my knowledge on this blog in the first place.
Happy coding!
@Edin
Hi I have one another question that how could I pre-populate the form fields with database values? Eg:- like first name, last name, address kind of details.
Please help me in getting this..
Thanks in advance..
Kalyan
Hi Kalyan,
Sorry for the delay.
I think you can populate it using Data View Web Part from SharePoint Designer. It can display data from SQL source and then you can use java script / XSLT to get it into the fields.
Hey Edin,
This was great and really helped me. One think I am noticing though, if you Cancel from the form, and get prompted ‘Do you definitely want to leave without saving changes, etc’, and then click Ok to save changes…. I don’t think PreSaveAction gets called!?
Cheers
Gavin
does this test check the time (hours and minutes)?
how can I change the time of such a control?
How to validate start Time before end time?
This comment has been removed by the author.
This comment has been removed by the author.
Hi Edin,
I copied your code and paste it in Content Editor Web Part in newform.aspx by sharepoint designer, but i get the error message when i testing the page:
Webpage Script Errors
Message: Object expected
Message: Object doesn’t support this property or method
here is the code i used:
[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
}
[/script]
Can you please suggest on this?
Thanks in advance..
Hi Ma Zhe,
It seems that you haven’t included the necessary function “getTagFromIndentifierAndTitle”. You can find the code at http://edinkapic.blogspot.com/2007/08/hide-field-from-newformaspx.html
This comment has been removed by the author.
This comment has been removed by the author.
The code seems correct, check that the field names (“Start Date” and “End Date”) are well written.
Hi Edin,
thank you very much, as you said i lost the function “getTagFromIndentifierAndTitle”. it is work correctly now!!
thank you again!!
This comment has been removed by the author.
Great post – the script works perfectly. Just blogged about it at http://sharepointapplied.wordpress.com/2009/01/08/sharepoint-forms-date-validation-using-javascript/
Keep them coming!
Greg
Hi
I want to hide some fields based on drop down values selected?
can this be doone?
Great post. This helped me a lot.
Many thanks for sharing this.
hi ,
is your code working for sharepoint control i.e date picker control. if so, how can i call the function
Hi,
It should work because the validation function is called for the form, not for the individual items. Your main concern should be how to access the control value with JavaScript.
Regards,
Hi,
If my “start date” & “end date” inclulded the time value. how to control the time validation in this javascript?
thx
Hi Edin,
But it seems dosen’t work. I’ve try to select the start time > end time. It can be saved. On the other hand, if I select the start date > end date, it’ work. It cannot be saved and prompt message !!
thx
Hi Edin. I’ve been using the PreSaveAction function on my new and edit forms for some time now. Works great, except I am not able to come up with a clean way of checking a date/time against another date/time, since SharePoint breaks that out into an input and two selects. There’s no good tags to grab for the two selects for the hours and minutes.
Example of minutes select:
select name=”ctl00$m$g_b6d12889_a442_4619_a490_ad2198622376$ctl00$ctl04$ctl11$ctl00$ctl00$ctl04$ctl00$ctl00$DateTimeField$DateTimeFieldDateMinutes” id=”ctl00_m_g_b6d12889_a442_4619_a490_ad2198622376_ctl00_ctl04_ctl11_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDateMinutes” dir=”ltr”
No title tag on these selects. Seems Microsoft should have used a title attribute on these that just appended ‘Hours’ and ‘Minutes’ so they could be easily matched up with the proper input tag that makes up the date. And they even went to the trouble to add a label tag for the hours and minutes and hide those. Looks like the td tag that the two selects are within won’t work either, since it just has a generic class. Ideas?
Hi Edin and Tony,
I have the same challenge as Tony – I have the javascript working fine on my calendar event start date and end date (the end date cannot occur before the start date), but I have not been able to find a way to verify that the appointment end time does not occur before the start time for a same day appointment. Has anyone sorted this out?
i am using SP 3.0….I really cant make the code work, please help!!!
I tried posting the following in content editor web part n also newform.aspx in contentplaceholder. both seperately but it is not owrking…!!!! i also changed the “Start Date” to “Start Time” nothing works. please guide where am i going wrong.
thanks
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;
}
hai i need to compare one textbox and drop down values.if both are same i need to display one popup box and dispaly like name already exists.it should happend in newform.aspx,editform.aspx.how can i write the javascript for this..cn u help me ..its very urgent..
thanks in advance..
this does not work if my date fields are used across various locales…right? Because it is assuming that date is in YYYYMMDD format …any code which can work across locales?
Thanks.
I want to use this in EditForm.aspx.
But I get a “Parser Error” since the EditForm.aspx uses:
<%@ Page language=”C#” … at the top and hence I cannot use:the JavaScript Tag inside PlaceHolderMain.
Any ideas how to resolve this?
Great post. Saved me a ton of searching and work.
JavaScript is a good program and very easy to use. I don´t like a complex program. I prefer javascript because i consider it like a device very eficient and it have a good quality.
I always looking for the quality that is why i prefer to buy viagra because i always have a great result in my sexual life.
i have a custom list form added to a list. i have a textbox and a dropdown list. depending on the value of dropdown list i need to enable the textbox(which is disabled initially). am new to sharepoint can u just tel me where to start with and how to access these controls using javascript if we add scripts to do the above function. please guide me where to find those javascripts code readily available.. thanks..
hi i have found a solution on my own for the prob i stated above. there was a new issue which am facing with now . in a form what i need to do is to enable a textbox when a particular value is chosen in a dropdown list. the presave action function is used already for some scripting purpose. i need to call a javascript function as soon as the value in dropdown list is chosen. can u please guide me? thanks..
Hi Rajkumar,
You can use the onchange event for the dropdown control.
select name=”ComboBox” onchange=”javascript:YourFunction()”
Hi Edin,
After lot of research I visited your site and looks like this is the perfect solution, but can you please help me as I have Start time and end time in the calendar. Field names are start time = EventDate and end time = EndDate. I really appreciate if you could post something sooner.
Thanks in Advance.
hi edin,
that worked fine.. tanks u so much……..
Hi Edin,
Your script worked perfect for me except it should even validate the time i.e. end time should always be 40 minutes greater than start time. I am looking forward for this solution.
Thanks
Kiran
hi,
can any1 explain in detail what does
“__designer:bind=”{ddwrt:DataBind(‘i’,concat(‘ff1′,$Pos),’Value’,’ValueChanged’,’ID’,ddwrt:EscapeDelims(string(@ID)),’@Title’)}” it do? this syntax comes as an attribute to . can any1 explain please? thanks
Hi Edin,
I am using a layout form and have to validate the date validations for a publishing site. I wanted to make sure that before publish is clicked i can validate the controls.
Please let me know your suggestions
can I do this by comparing between two lists, for example I have 2 lists list A and List B,List A contains block-out date field. once in list A block out date is added based on this in the List B it should not allow the user to add an item on this particular date. can you please give me posible solutions
great solution, Thanks heaps!
I get the Error Messages, but it still does a post to the list.
_spBodyOnLoadFunctionNames.push(“Check”);
function Check(){
if ( CheckEndDate()){
return false;
}
if ( CheckCompDate()){
return false;
}
return true;
}
function CheckEndDate()
{
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 true; // Cancel the item save process
}
return false; // OK to proceed with the save item
function CheckCompDate(){
var date1 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Start Date”);
var arrDate1 = date1.value.split(“/”);
var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);
var date3 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Requested Completion Date”);
var arrDate3 = date3.value.split(“/”);
var useDate3 = new Date(arrDate3[2], arrDate3[1]-1, arrDate3[0]);
if(useDate1 > useDate3)
{
alert(“The Requested Completion Date cannot happen earlier than the Start Date”);
return true; // Cancel the item save process
}
return false; // 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];
}}}
Hi Edin,
I have copied all your function hideFields(),function getTagFromIdentifierAndTitle(tagName, identifier, title),added necessary codes in function PreSaveAction() and added _spBodyOnLoadFunctionNames.push(“hideFields”); but i get the error as ‘parentNode’ is null or not an object…and when i put alert(control); its returning me null..I dont know why this is happening and what’s the problem..pls help me out Edin..
Does not seem to work in SharePoint 2013. The view-source shows… input type=”submit” name=”ctl00$PlaceHolderMain$ctl00$RptControls$btnOK” value=”Save” onclick=”if (SPClientForms.ClientFormManager.SubmitClientForm(‘WPQ2’)) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(“ctl00$PlaceHolderMain$ctl00$RptControls$btnOK”, “”, true, “”, “”, false, false))” id=”ctl00_PlaceHolderMain_ctl00_RptControls_btnOK” class=”ms-ButtonHeightWidth” /> …so there is, apparently, no hook to PreSaveAction. Do you hvae any suggestions for SharePoint 2013?
Hi mkamoski,
The code is still valid for List Forms. It seems that you are using custom JS-rendered forms. In SP2013 client-side rendered forms (CSR) you have to redefine the SPClientForms.ClientValidation function instead. Please check this URL for more information: http://blog.vgrem.com/2014/03/14/introduction-to-client-forms-validation-in-sharepoint-2013/
I have due date field (date and time) and I want to see if it is empty (user did not fill it out) in the PreSaveAction – how can I do this ? Basically I want users to fill out the required Due Date field because the SharePoint 2010 default validation doesn’t work when I use a custom Submit button (the reason I am using a custom button instead of SP-SaveButton is to redirect after submission). Tried everything but can’t seem to check if the Due Date field is empty and if it is to Alert user. Thanks.
You will have to use the standard ASP.NET button onclick action to do the custom validation in this case.