Validating forms in SharePoint (PreSaveAction)

There might be few ways of validating columns in SharePoint, specially the new OOTB feature in SharePoint 2010, however if you want to customise the validation to business needs, these are nor enough. 
For example, I need to make only one of the two available fields mandatory. If either one of them is filled by the user, validation is passed, or user should be notified.

The Solution

SharePoint uses JavaScript validation when a form is submitted. When I looked deeper, I found this code on "Save" button click:

if (!PreSaveItem()) return false;


In the above JavaScript, "PreSaveItem" calls another function called "PreSaveAction". If you define this function in NewForm.aspx or EditForm.aspx in the list, you can write all custom validation code in this function. For example:

function PreSaveAction(){
    var ctrl = $('#controlName');
    if(ctrl.val() == 'test'){
       return true;
    }
    else{
       return false;
    }
}

If you want to target particular List you can write something like this:

var url = window.location.href;
if(url.indexOf('/Lists/LibraryName/NewForm.aspx') != -1){
    //perform validation
}


Instead of modifying OOTB forms (newform and editform), we should use "AdditionalPageHead" which is explained in THIS article.

Important

If you write the PreSaveAction in reference JavaScript file (javascript.js), it will not work, meaning, PreSaveItem will not invoke custom PreSaveAction function, the function has to be defined in a custom form. Therefore either use AdditionalPageHead or modify the OOTB forms itself.
 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.