Sunday, August 6, 2017

SharePoint: Using PreSaveAction Function on SharePoint list forms

SharePoint: Using PreSaveAction Function on SharePoint list forms


While working with SharePoint list forms especially custom list forms, where UI is not typical SharePoint UI. We do have a requirement to validate fields before form submits. PreSaveAction function allows to override functionality when Save button is clicked. PreSaveAction function executes the code written for validation on click of Save button.




function PreSaveAction(){
    var itemDue = $("input[title='Task Due Date Required Field']").val();
    var dueDate = new Date(itemDue);
    var currentDate = new Date();
if(dueDate  <= currentDate )
{
alert("Due date should be greater than current date.");
return false;
}
return true;


    }




The above code with PreSaveAction function for validation to display alerts or messages on Save button click was used.




This method is called when save button is clicked and alert messages are displayed in case of invalid input.

Issue: If you are using Custom Save button (to navigate to other pages etc after save) on custom list form, then above code will not work or to say, above mentioned PreSaveAction will not be called.
Cause: Default Save button calls PreSaveItem method, which in turn calls PreSaveAction for any validations. So when we use custom button, like below, PreSaveItem method is not called on button click.


Custom Save button - <input type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={home.aspx}')}" />

Solution: Call to PreSaveItem method is to be included in onclick event of button, as shown below


Changed to - <input type="button" value="Save" name="btnSave" onclick="if (!PreSaveItem()) return false; {ddwrt:GenFireServerEvent('__commit;__redirect={home.aspx}')}" />

Highlighted code is added to custom button.

Note: If you are using "$(document).readyin your code, make sure PreSaveAction function is written outside this block, as in above code or else PreSaveAction method will not be called.

No comments:

Welcome to SharePoint Server 2019, a modern platform for choice and flexibility

“Without continual growth and progress, such words as improvement, achievement, and success have no meaning.” Benjamin Franklin Thi...