none
SharePoint 2013 - Validate People Picker Field with JQuery RRS feed

  • Question

  • Hello Community,

    I'm working in SharePoint 2013 and I would like to use JQuery in a new and edit form to validate two People Picker fields.  Basically, I want to compare the values of two People Picker fields and ensure they are not the same value.  Has anyone else ever done this and if so can you provide guidance and code?

    Thanks!

    Tom


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Thursday, December 21, 2017 10:35 PM

Answers

  • OK, here's what I finally worked out, and this works great!

    <script src="/sites/cm/SiteAssets/JQuery/jquery.SPServices.min.js" type="text/javascript"></script>
    <script src="/sites/cm/SiteAssets/JQuery/jquery-3.1.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
    _spBodyOnLoadFunctionNames.push("initEndDateEvent");
    
    function PreSaveAction() {
    
       var label1 = "TS Manager";
       var variable1 = "fldTSManager";      
       var label2 = "Change Installer";
       var variable2 = "fldChangeInstaller";
       
       var userNameTS = checkPPC(label1, variable1);   
       var userNameCI = checkPPC(label2, variable2);   
       comparePPC(userNameTS, userNameCI);
       
       function checkPPC(label, variable){
       
    	   var tempcon;
    	   var fieldValue = "";	   
    	   var fieldLabel = label;
    	   var tr = GetFieldRow(fieldLabel);
    	   var controls;
    		
    		// retrieve the table row that assigned to is found
    		controls = tr.getElementsByTagName("DIV");
    		for(var k=0; k < controls.length; k++) {
    			if(controls[k].id.indexOf("UserField_upLevelDiv") > 0) {
    				tempcon = controls[k].textContent.trim();
    				if (controls[k].textContent.trim() == fieldValue || controls[k].textContent == null){
    					alert("Please assign a " + fieldLabel + "."); 
    					return false; // Cancels the save item process
    				} else {					
    					alert(fieldLabel + ": User = " + tempcon);
    					var userName = tempcon;
    					return userName;
                                            //return true;
                                            //return;
    				}
    			}
    		}
       }
    	
    	// gets the parent node of assigned to 
    	function GetFieldRow(fieldLabel) {
    		var nobrs = document.getElementsByTagName("nobr");
    		for(var i=0; i < nobrs.length ; i++) {
    			if (nobrs[i].textContent == fieldLabel) {
    				var tr = GetParentByTagName("TR", nobrs[i]);
    				return tr;
    			}
    		}
    	}
           	
    	// finds the parent node of the assigned to field
    	function GetParentByTagName(parentTagName, childElementObj) {
    		var parent = childElementObj.parentNode;
    		while(parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
    			parent = parent.parentNode;
    		}
    		return parent;
    	}
    } 	
    
    function comparePPC(variable1, variable2){
    
         //alert("test");
         alert("variable1 " + variable1 + " variable2 " + variable2);
         
         if(variable1 === variable2){
    
           //alert("Test");
           alert("The TS Manager is " + variable1 +  " and the Change Installer " + variable2 + ", these two fields cannot be the same person.");
           return false;
    
         } else {
    
           alert("The variables do not match");     
    
         }
    }
    
    </script>

    The core of this solution was an answer provided by "splassle" in the post below:

    https://social.msdn.microsoft.com/Forums/office/en-US/f1c2a651-a0fb-484d-af33-e7084439b6c8/validate-sharepoint-people-picker-using-javascript

    Thanks to Jerry Zy, SAllen MCSD, and Ratula Raut's for their input!

    Tom Molskow

    SharePoint Gypsy


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    • Marked as answer by Tom Molskow Thursday, December 28, 2017 5:56 PM
    Thursday, December 28, 2017 5:56 PM

All replies

  • Try:
    if ($("input[title='ColumnName']").val() === $("input[title='ColumnName']").val()) {}
    Or Try: 
    $("input[title='ColumnName']").val() !== $("input[title='ColumnName']").val(){}


    Thursday, December 21, 2017 10:49 PM
  • Or if aria-label is used:

    if ($("input[title='ColumnName']").attr("aria-label") === $("input[title='ColumnName']").attr("aria-label")) {}

    Thursday, December 21, 2017 10:55 PM
  • What is aria-label?

    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Friday, December 22, 2017 1:24 AM
  • I'll try both of those and then LYK - thanks!

    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Friday, December 22, 2017 1:25 AM
  • Hi Tom,

    Here is a code snippet for  your to check the two person field value and then do validation in PreSaveAction, if they are the same, then it will pop up a message and not save the data.

    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
    <script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
    <script type="text/javascript">
    function PreSaveAction()
    {
        var value1=getUserFromPeoplePicker('person1');
        var value2=getUserFromPeoplePicker('person2');
        console.log(value1);
        console.log(value2);
        if(value1==value2)
        {
           alert("Two Person fields can't  select the same person");
           return false;
        }
        else
        {
          return true;
        }
    
    }
    
    function getUserFromPeoplePicker(title) {
                //Get the people picker field
                var ppDiv = $("div[title='" + title + "']")[0];
                //cast the object as type PeoplePicker
                var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
    
                //Get list of users from field (assuming 1 in this case)
                var userList = peoplePicker.GetAllUserInfo();
                var userInfo = userList[0];
                console.log(userInfo);
                var userLoginName;
                
                //The description field contains the login info without the lookup extras.  In new forms this 
                //field can be undefined depending on the field being checked.  Only check if userInfo is
                //initialized.
                if (userInfo != null) {
                    
                    userLoginName=userInfo.Key;
                }
    
                return userLoginName;
            }
    </script>
    

    the parameter for getUserFromPeoplePicker function is the field Title, here is the result:


    Thanks

    Best Regards


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Friday, December 22, 2017 10:12 AM
  • Both of this method and the one you listed below methods return undefined - see script below:

    <script src="/sites/cm/SiteAssets/JQuery/jquery.SPServices.min.js" type="text/javascript"></script><script src="/sites/cm/SiteAssets/JQuery/jquery-3.1.1.min.js" type="text/javascript"></script><script type="text/javascript">
    
    _spBodyOnLoadFunctionNames.push("initEndDateEvent");
    
    function PreSaveAction()   
    {
         var sTypeChange= $("select[title='Type of Change'] option:selected").text();
         var ppkDOEmail1 = $("input[title='DeliveryOwner']").val();
         var ppkDOEmail2 = $("input[title='DeliveryOwner']").attr("aria-label");
         
         if(sTypeChange == '(None)')
         {
            alert("Please select a Type of Change - " + sTypeChange + " is not an acceptable value. " )
            return false;
         }
         else
         {
            //alert("True");
            alert("PPK Emails " + ppkDOEmail1 + " " + ppkDOEmail2 );
            return true;
            //return false;
         }
                 
    }
    
    </script>


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Friday, December 22, 2017 3:40 PM
  • @Jerry Zy - Sorry, this just isn't working - my code is below - am I missing something?

    <script src="/sites/cm/SiteAssets/JQuery/jquery.SPServices.min.js" type="text/javascript"></script><script src="/sites/cm/SiteAssets/JQuery/jquery-3.1.1.min.js" type="text/javascript"></script><script src="/_layouts/15/clientpeoplepicker.js" type="text/javascript"></script><script type="text/javascript">
    
    _spBodyOnLoadFunctionNames.push("initEndDateEvent");
    
    function PreSaveAction()   
    {
         var sTypeChange= $("select[title='Type of Change'] option:selected").text();
         //var ppkDOEmail1 = $("input[title='Delivery Owner']").val();
         //var ppkDOEmail2 = $("input[title='Delivery Owner']").attr("aria-label");
         var ppkDOEmail3 = getUserFromPeoplePicker('Delivery Owner');
         console.log(ppkDOEmail3);
         
         if(sTypeChange == '(None)')
         {
            alert("Please select a Type of Change - " + sTypeChange + " is not an acceptable value. " )
            return false;
         }
         else
         {
            //alert("True");
            //alert("PPK Emails " + ppkDOEmail1 + " " + ppkDOEmail2 + " " + ppkDOEmail3 );
            alert("PPK Emails " + ppkDOEmail3);
            return true;
            //return false;
         }
    
        //Validate Installer and Verifier are Different People   
           
    }
    
    function getUserFromPeoplePicker(title) 
    {
                
       //Get the people picker field
       var ppDiv = $("div[title='" + title + "']")[0];
       //cast the object as type PeoplePicker
       var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
    
       //Get list of users from field (assuming 1 in this case)
       var userList = peoplePicker.GetAllUserInfo();
       var userInfo = userList[0];
       console.log(userInfo);
       var userLoginName;
            
       //The description field contains the login info without the lookup extras.  In new forms this 
       //field can be undefined depending on the field being checked.  Only check if userInfo is
       //initialized.
       if (userInfo != null) {
                    
       userLoginName=userInfo.Key;
       }
          return userLoginName;
       }
    
    </script>


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy


    • Edited by Tom Molskow Friday, December 22, 2017 6:49 PM
    Friday, December 22, 2017 5:55 PM
  • Hi,

    Please put the code under the list form page PlaceHolderMain tag like capture below:

    And you can check the people value using console.log like:

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, December 25, 2017 2:49 AM
  • Hi,

    I am checking to see how things are going there on this issue. Please let us know if you would like further assistance.

     

    Thanks

     

    Best Regards


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Wednesday, December 27, 2017 9:06 AM
  • Hi Tom,

    Try with <g class="gr_ gr_43 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" data-gr-id="43" id="43">below mentioned</g> code with username
    var user1 = getUserDetail("ppl1");
    console.log(user1);
    var user2 = getUserDetail("ppl2");
    console.log(user2);
    if (user1 === user2) {
        alert("same user");
    } else {
        alert("different user ");
    }
    
    function getUserDetail(columnName) {
        var userName;
        var controlName = columnName;
        var ppDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']"); // Select the People Picker DIV
        var ppEditor = ppDiv.find("[title='" + controlName + "']"); // Use the PP DIV to narrow the jQuery scope
        var spPP = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id]; // Get the instance of the People Picker from the Dictionary
    
        //ppEditor.val("jasonscript\\jason");					// Set the value
        spPP.AddUnresolvedUserFromEditor(true); // Resolve the User	if (!spPP.HasInputError)
        {
            var userKeys = spPP.GetAllUserInfo();
            if (userKeys.length > 0) {
                var myUser = userKeys[0];
                userName = myUser['Key'];
            } else userName = "No data"
        }
        return userName;
    }
    //You can also use same code to get <g class="gr_ gr_55 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" data-gr-id="55" id="55">userid</g> with userName

    function GetUserId(userName) {
                var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
            
                /// make an ajax call to get the site user
                $.ajax({
                    url: siteUrl + "/_api/web/siteusers(@v)?@v='" + 
                        encodeURIComponent(accountName) + "'",
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: function (data) {
                        ///popup user id received from site users.
                        console.log("Received UserId" + data.d.Id);
         return data.d.Id;
                        
                    },
                    error: function (data) {
                        console.log(JSON.stringify(data));
                    }
                });
            }

    • Edited by Rutuja Raut Friday, January 5, 2018 12:00 PM
    Wednesday, December 27, 2017 1:00 PM
  • @Moderator - I am trying the new suggestions today - thanks!

    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Wednesday, December 27, 2017 2:22 PM
  • Hello Rutuja,

    I did try your code but unfortunately it keeps coming back with a false positive "same user undefined undefined". I'm not seeing how the two input[title functions are called, and their alerts never fire.  What am I missing?  The code, as I slightly modified it, is below.  (BTW, I tried it with both the column name and the field name).

    Thanks!

    Tom

    $(document).ready(function(){
    
    	var peoplePickerUserName1;
    	var peoplePickerUserName2;
    	var column1="Delivery Owner";
    	var column2="TS Manager";
     
    
    $("input[title='" + column1 + "']").focusout(function () {   
    
        var loginName = $("span.ms-entity-resolved").attr("ID");
    
        var start = loginName.indexOf(":");
    
        var end = loginName.indexOf("_Processed");
    
        var finalUserName = loginName.substring(start-1, end);
        
    		alert(finalUserName);
    	
        peoplePickerUserName1=finalUserName;//get first user name
       
     });
     
    
    $("input[title='" + column2 + "']").focusout(function () {    
    
        var loginName = $("span.ms-entity-resolved").attr("ID");
    
        var start = loginName.indexOf(":");
    
        var end = loginName.indexOf("_Processed");
    
        var finalUserName = loginName.substring(start-1, end);
        
    		alert(finalUserName);
    	
        peoplePickerUserName2=finalUserName;//get second user name
       
     });
     
    //GetUserId("domain\user");
     if(GetUserId(peoplePickerUserName1)==GetUserId(peoplePickerUserName2)){
    	 
    	 alert("same user " + peoplePickerUserName1 + " " + peoplePickerUserName2);
    	 
        }
    
    });
    
    function GetUserId(userName) 
    {
                 
        /// change this prefix according to the environment.
        /// In below sample, windows authentication is considered.
            var prefix = "i:0#.w|";
        /// get the site url
            var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        /// add prefix, this needs to be changed based on scenario
            var accountName = prefix + userName;
    
        /// make an ajax call to get the site user
    		 $.ajax({
    			 url: siteUrl + "/_api/web/siteusers(@v)?@v='" + 
    				 encodeURIComponent(accountName) + "'",
    			 method: "GET",
    			 headers: { "Accept": "application/json; odata=verbose" },
    			 success: function (data) {
    	///popup user id received from site users.
    				 console.log("Received UserId" + data.d.Id);
      return data.d.Id;
    				 
    			 },
    			 error: function (data) {
    				 console.log(JSON.stringify(data));
    			 }
    		 });
    }
    
    


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Wednesday, December 27, 2017 4:59 PM
  • Hey Jerry,

    My code is below, but now embedded directly into the EditForm.aspx, it doesn't even seem to fire off.  What am I missing?

    Thanks!

    Tom

    <asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server">
    	<img src="/_layouts/15/images/blank.gif?rev=40" width='1' height='1' alt="" data-accessibility-nocheck="true"/>
    </asp:Content>
    <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
    <script src="/sites/cm/SiteAssets/JQuery/jquery-3.1.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
    <script type="text/javascript">
    function PreSaveAction()
    {
        var value1=getUserFromPeoplePicker('Delivery Owner');
        var value2=getUserFromPeoplePicker('TS Manager');
        alert("value1 " + value1);
        alert("value2 " + value2);
        console.log(value1);
        console.log(value2);
        if(value1==value2)
        {
           alert("Two Person fields can't  select the same person");
           return false;
        }
        else
        {
          return true;
        }
    
    }
    
    function getUserFromPeoplePicker(title) {
                //Get the people picker field
                var ppDiv = $("div[title='" + title + "']")[0];
                //cast the object as type PeoplePicker
                var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
    
                //Get list of users from field (assuming 1 in this case)
                var userList = peoplePicker.GetAllUserInfo();
                var userInfo = userList[0];
                console.log(userInfo);
                var userLoginName;
                
                //The description field contains the login info without the lookup extras.  In new forms this 
                //field can be undefined depending on the field being checked.  Only check if userInfo is
                //initialized.
                if (userInfo != null) {
                    
                    userLoginName=userInfo.Key;
                }
    
                return userLoginName;
            }
    </script>
    


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Wednesday, December 27, 2017 6:33 PM
  • Hi Tom, 

    This script will trigger when clicking Save Button in the edit form, please try again with Save Button click, in my environment it works as expected:

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, December 28, 2017 3:44 AM
  • @Jerry - Yes, I did click Save, it didn't work

    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    Thursday, December 28, 2017 5:42 PM
  • OK, here's what I finally worked out, and this works great!

    <script src="/sites/cm/SiteAssets/JQuery/jquery.SPServices.min.js" type="text/javascript"></script>
    <script src="/sites/cm/SiteAssets/JQuery/jquery-3.1.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
    _spBodyOnLoadFunctionNames.push("initEndDateEvent");
    
    function PreSaveAction() {
    
       var label1 = "TS Manager";
       var variable1 = "fldTSManager";      
       var label2 = "Change Installer";
       var variable2 = "fldChangeInstaller";
       
       var userNameTS = checkPPC(label1, variable1);   
       var userNameCI = checkPPC(label2, variable2);   
       comparePPC(userNameTS, userNameCI);
       
       function checkPPC(label, variable){
       
    	   var tempcon;
    	   var fieldValue = "";	   
    	   var fieldLabel = label;
    	   var tr = GetFieldRow(fieldLabel);
    	   var controls;
    		
    		// retrieve the table row that assigned to is found
    		controls = tr.getElementsByTagName("DIV");
    		for(var k=0; k < controls.length; k++) {
    			if(controls[k].id.indexOf("UserField_upLevelDiv") > 0) {
    				tempcon = controls[k].textContent.trim();
    				if (controls[k].textContent.trim() == fieldValue || controls[k].textContent == null){
    					alert("Please assign a " + fieldLabel + "."); 
    					return false; // Cancels the save item process
    				} else {					
    					alert(fieldLabel + ": User = " + tempcon);
    					var userName = tempcon;
    					return userName;
                                            //return true;
                                            //return;
    				}
    			}
    		}
       }
    	
    	// gets the parent node of assigned to 
    	function GetFieldRow(fieldLabel) {
    		var nobrs = document.getElementsByTagName("nobr");
    		for(var i=0; i < nobrs.length ; i++) {
    			if (nobrs[i].textContent == fieldLabel) {
    				var tr = GetParentByTagName("TR", nobrs[i]);
    				return tr;
    			}
    		}
    	}
           	
    	// finds the parent node of the assigned to field
    	function GetParentByTagName(parentTagName, childElementObj) {
    		var parent = childElementObj.parentNode;
    		while(parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
    			parent = parent.parentNode;
    		}
    		return parent;
    	}
    } 	
    
    function comparePPC(variable1, variable2){
    
         //alert("test");
         alert("variable1 " + variable1 + " variable2 " + variable2);
         
         if(variable1 === variable2){
    
           //alert("Test");
           alert("The TS Manager is " + variable1 +  " and the Change Installer " + variable2 + ", these two fields cannot be the same person.");
           return false;
    
         } else {
    
           alert("The variables do not match");     
    
         }
    }
    
    </script>

    The core of this solution was an answer provided by "splassle" in the post below:

    https://social.msdn.microsoft.com/Forums/office/en-US/f1c2a651-a0fb-484d-af33-e7084439b6c8/validate-sharepoint-people-picker-using-javascript

    Thanks to Jerry Zy, SAllen MCSD, and Ratula Raut's for their input!

    Tom Molskow

    SharePoint Gypsy


    Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy

    • Marked as answer by Tom Molskow Thursday, December 28, 2017 5:56 PM
    Thursday, December 28, 2017 5:56 PM
  • Please find updated code in comment
    Friday, January 5, 2018 12:00 PM