Wednesday, June 13, 2012

SharePoint People Editor Client Validation - The Easy Way

There are quite a few blogs that discuss how to validate the SharePoint 2010 people editor on the client side. These range from very simple DOM checks to full blown custom solutions. The problem I encountered in looking at these is that most assume that the user will click the check names validate button on the control first, before the control is validated on the client.  I don't like this assumption, as it may or may not be valid, depending on the user.  Hence the solution below.  

My first thoughts were as follows.  When using a people editor manually, the steps taken are first to type in the user or group, then to click the validate button. Doing so makes an asynchronous call back to the server (internal ajax in the people editor I think, although Fiddler shows the entire page being posted... I will look at this further when time allows).  If the control is valid, great, proceed. Otherwise, the value would be manually fixed, and rechecked until it passed validation. Let's do just that, but in code.  

This requires two simple steps: 
  1. Programmatically click the People Editor check button.
  2. Determine if the control is valid after waiting for the check to finish.
Clicking the button is easy with jQuery.  First, in your aspx or ascx where the people editor exists, lets create a JavaScript variable for the people editor client id:

<script type="text/javascript" language="javascript"> var peId = '<%= pe.ClientID %>'; </script>
Now we can create a function that will click the people editor check names button for us, wait for the async response, and check if the control is valid.
 <script type="text/javascript" language="javascript">  
 function CustomValidatePeopleEditor() {  
   $("#" + peId + '_checkNames')[0].click();  
   setTimeout(function() {  
     if ($("#" + peId).find('*[isresolved="False"]').length > 0) {  
       // Do stuff for an invalid editor (only writing the the f12 console here)  
       console.log('false');  
   } else {  
       // Do stuff for a valid editor (only writing the the f12 console here)  
       console.log('true');  
     }  
   }, 500);  
 }  
 </script>  
Note that setting the timeout is not great, but should work even on an air card.  With a dial up connection you may be sol, but who uses dial up?  Still, just to be sure, an additional check should be made on the validity of the control at the time the form is posted.  You can do this in your submit code, on a domain object, in a helper class, or anywhere else that you see fit...
Pretty easy, no?