Validating Taxonomy Metadata Field in Javascript (Single Value Field)

Many of us have requirements of validating Metadata Fields in the client side itself, thus giving a nice little alert message and avoiding save....very interactive and nice....

Find below a script that you can use for the same.

All you need to do is, go to your Document Library or List, Go to the Edit Form WebPart Page, add a Content editor WebPart, edit the HTML Source and put this script inside... below the Edit Form and Save the Page back (Page ribbon -> Stop Editing)....

The script is inside the PreSaveAction() that is called by the SharePoint Save method, which if returns false, the validation is considered failed and SharePoint does not save the data..
--------------------------------------------------

<script type="text/javascript">
function PreSaveAction()
{

var iRef = document.getElementsByTagName("div");

var arr = new Array();

for(var i=0;i<iRef.length;i++)
{
  if(iRef[i].id.indexOf("editableRegion")>=0)
  {
    var itemFound = iRef[i];
    if(itemFound.innerText.length==1)
    {
      continue;
    }
    for(var j=0;j<arr.length;j++)
    {
      if(arr[j]==itemFound.innerText)
      {
          alert("Classification ("+itemFound.innerText+") already exists! \nPlease choose a different classification.")
          return false;
       }
    }
      arr.push(itemFound.innerText);

  }
}

return true;
}</script>

Comments

  1. what exactly are you validating against here? I have a requirement to only allow certain terms in a field depending on a property of the web. I have some script that checks some metadata in the property bag of the SPWeb and would then like to remove the term assoicated. e.g. Terms Level 1, Level 2 etc. and if you are on a Level 2 site remove the term Level 2.

    Any help would be greatly appreciated.

    ReplyDelete

Post a Comment

Popular posts from this blog

Using External Content Types with Stored Procedures with Input Parameters

Windows 7 Blue Screen because of ConnectiFy

HTTPS Site InfoPath Issue : You do not have permissions to access a web service that provides data required for this form to function correctly