Tuesday, December 9, 2014

SharePoint Form Validation via PreSaveAction Method 

Context: Conditional validation in SharePoint can be done via out of the box option i.e. List Validation. There are some use cases when one cannot make use of the List Validation. I also got a situation where I want to validate a column based on another column of type Taxonomy. Since Taxonomy type of columns doesnot appear in the List Validation, I used Javascript and overridden default PreSaveAction() Method to implement my custom conditional validation logic.

Scenario: Here, I am creating an example and this is not the actual implementation. 
I created a custom list and added two columns in it i.e. Country (Taxonomy) and City (Text). So, whenever a user enters ‘Germany’ in the country field, the city field will become a mandatory field and ask from the user to fill the value before he wants to save the list item.


Solution: I added a content editor webpart on the NewForm.aspx and later added code in it. The code consist of a method ‘PreSaveAction()’ which is actually overriding the default PreSaveAction method bind with the Click event of the ‘Save’ button on a NewForm.aspx.


The following is how my list looks like along with the column validation;


The following is how my conditional validation looks like once I added my code in the content editor webpart;


The JavaScript code for achieving the above result is as follows;