Introduction



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.

Scenario



With a custom SharePoint list form with custom UI (not SharePoint UI) and after save or cancel, we want to redirect user to home page. There is a field "Employee Number" which is of type "Number" and range is "6-10". Also we want the user to attach files while creating a new item. For invalid input for "Employee Number field", when user clicks on Save button, page postback happens and if validation fails, validation message is displayed. A validation message should be displayed without postback ie. client side validation.

Solution



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

<script type="text/javascript" src=""></script>
<script type="text/javascript">
$(document).ready(function(){
   // Here i added code for other functionalities
});
//PreSaveAction code to validate
 function PreSaveAction()
{
    var empNum = $('input[title="Employee Number"]').val();
    var table = $("#idAttachmentsTable tr");
 
    if(empNum < 6 || empNum > 10)
   {
      alert('Please provide employee number with digit range 6-10');
      return false;
   }
   else
   {
   if (table == null || table.length == 0)
    {      
        $("#idAttachmentsRow").attr("display",'none');     
        alert("Please Attach Files");
        return false ;
    }
    else
    {
        return true;
    }
   }
}
</script>

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

Important Update




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).ready" in your code, make sure PreSaveAction function is written outside this block, as in above code or else PreSaveAction method will not be called.

Hope it is useful.