8/9/12

SharePoint How to Prevent Edit Item Form Submit

In SharePoint, the Edit Item Form is used to update a list item. In some instances, we may want to prevent the user from updating the record because of some rule validation and block the form submit on the client side. On a simple HTML form, we could use the preventDefault() function or just return false from the raised event handler, but this does not work on SharePoint because the Save button calls a specific JavaScript function to do the submit.

If you inspect the Save button on the form, you can see that there is a call to a PreSaveItem function. This function can be used to add code to perform one or more tasks that may be required in order to allow the item to be updated. I often use this function when I have an item that is associated to some business rule constraint defined in another list or a web service, and I need to make sure that a certain condition is met. To implement this function, you can open the edit item form and embed the following JavaScript (or add a reference to a JavaScript file with the same content):


function PreSaveItem(){
       var allowPostback = RuleValidation();
       if (!allowPostback)
          alert(“Sorry, we are unable to update this record …”);
       return allowPostback;
}

function RuleValidation(){
  //todo  ajax or client object model call to check the constraints
}



If the custom rule validation function returns true the update is submitted. If the function returns false, we let the user know that there was a problem, and he/she can then make the necessary corrections.