jQuery to validate a people picker control for blank value in SharePoint

jQuery has made lives simpler by the validation techniques it uses. However, it can be big pain also the way it deals with various kind of controls. My case was to validate the people picker control.

The usual technique is to find the control, then match the value or text in the control to blank… and boom!!! you’re done with the validation.
But this seemed to work for the text boxes, drop downs, etc. The people picker, however, was returning by default the value – “&#160”. This is the blank value, but it never returned true upon comparison with blank.

So, the catch here is to find the correct control. It is not the people picker, instead you need to find the div with the id ‘divEntityData’. Then do the comparisons as in below code. It first checks the length, if nothing is entered. Later, if you’ve entered any value in the people picker, it will check whether it is resolved or not using the attribute “isresolved”. Use the below code for your reference.

function IsPeoplePickerValueResolved() { 
   var eEntityData = $("div[id='divEntityData']");
   if(eEntityData.length == 0)
   {
   		alert("Please enter a user for this user field");
   		return false;
   }
   else if(eEntityData.length > 0 ) 
   {
       var isResolved = eEntityData.attr("isresolved");
       if(isResolved == "True")
       {
	       return true;
       }
       else
       {
	     alert("Please select correct name and resolve it");
	     return false;
       }
   }
   else
   {    
	   return false;
   }
}

Hope you could save some time with this.

Advertisements