Pages

Monday, August 1, 2011

SharePoint : Validate controls before the item is saved via PreSaveAction() in SharePoint 2007/2010

I do have one requirement in which I need to check if they check one of the checkbox then they must have to enter the value. Without eventhandler or any custom code how could we do that?
We can achieve this thing via Content Editor WebPart and write JavaScript inside that. PreSaveAction() is manly used to validate controls before the item is saved( new item or edit).
How to do that?
Let us edit the page and add one content editor webpart , and add the javascript code in that content editor webpart and save page.
Sample of Javascript Code.
<script type="text/javascript">
function PreSaveAction()
{
var control = getTagFromIdentifierAndTitle("input","BooleanField","Other available");
var control1 = getTagFromIdentifierAndTitle("input","TextField","Other Value");
if(control.checked)
{
var StrToCheck= control1.value.replace(/^\s+|\s+$/, '');
//then we check for the length of the string if its 0 or not
if( StrToCheck.length==0 || StrToCheck =='0')
{
alert('Enter the value for Other');
}
}
else
{
control1.value=0;
}
return false;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
  var len = identifier.length;
  var tags = document.getElementsByTagName(tagName);
  for (var i=0; i < tags.length; i++) {
    var tempString = tags[i].id;
    if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
      return tags[i];
    }
  }
  return null;
}</script>

Hope this helps!!!
Disha Shah

1 comment:

  1. Does this work in SharePoint 2013? It looks like it does not. Is there a trick for 2013 to get it to work?

    ReplyDelete