Search This Blog

Tuesday 12 June 2012

Javascript PreSaveAction() in SharePoint 2010


You Can Use PreSaveAction function to execute any JavaScript Code in New or Edit Forms for any SharePoint List before Saving the item.

It Validate form without PostBack.

Syntax: 
PreSaveAction()
{
//Add Your JavaScript Code Here Then Return True Or False
return false; // Cancel the item save process
return true; // OK to proceed with the save item
}

“PreSaveAction” function is JavaScript function which allow programmer to write code with in this function which will execute just before saving records. Programmers can use this function in NewForm.aspx or EditForm.aspx. 

Code Example:

<script src="/Shared%20Documents/prototype.js" type="text/javascript"></script>
<script src="/Shared%20Documents/SPUtility.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction()    {
alert(SPUtility.GetSPField('Title').GetValue());
if(SPUtility.GetSPField('Title').GetValue() != null)
{
     alert('Validation passed, let SharePoint continue');
     return true;
}
else
{
alert('Validation failed, let SharePoint not continue');
     return false;

}
} </script>

To install, you’d simply place the JavaScript above into a Content Editor Web Part on your NewForm.aspx or EditForm.aspx

References:



3 comments:

  1. HI Mani,

    I need to validate a field called 'Project name' which gets created by workflow.
    This field is combination of three columns.

    I need to validate if this name already exists in the list.

    Please help

    ReplyDelete
    Replies
    1. Hi,

      Generally using SPUtility you can access fields which are available on the form (New/Edit), for more details about SPUtility, pls go to http://sputility.codeplex.com/.

      If you want to check whether particular field exists in the list then you have to go with SharePoint Client Object Model.

      Thanks

      Delete
  2. Can I make field required only when user clicks on rejected button on a task form?

    Thanks in advance

    ReplyDelete