How to validate SharePoint list for First and Last name should be unique in Office 365/SharePoint online/2010/2013/2016?

Hello SharePointers,

SharePoint online doesn’t allow two columns to be set as unique value for validation. Let us consider the business scenario, where first name and last name has to be unique in a SharePoint list. This can be achieved using REST API calls .

Below are the code snippet that will help you to do validation

$(document).ready(function(){
var isValid=0;

alert(“Inside Ready”);

$(‘nobr:contains(“Title”)’).closest(‘tr’).hide();

var siteurl = _spPageContextInfo.webAbsoluteUrl;
alert(siteurl);

$.ajax({
url: siteurl + “/_api/web/lists/getbytitle(‘Employee List’)/items??$select=Title,First_x0020_Name,Last_x0020_Name&$filter=((First_x0020_Name eq ‘”+firstName+”‘) or (Last_x0020_Name eq ‘”+firstName+”‘))&$top=5000”,
method: “GET”,
headers: { “Accept”: “application/json; odata=verbose” },
success: function (data) {
alert(“function sucess”);
if (data.d.results.length > 0 ) {
alert(“Yes”);
isValid=1;
alert(isValid);
}
},
error: function (data) {
alert(“Error: “+ data);
}
});

});

function PreSaveAction()
{

var firstName =$(“input[title=’First Name’]”);

if (firstName.val()==””)
{

alert(“First Name Cannot be Blank”);
return false;
}

var LastName =$(“input[title=’Last Name’]”);

if (LastName.val()==””)
{

alert(“Last Name Cannot be Blank”);
return false;
}

var siteurl = _spPageContextInfo.webAbsoluteUrl;
alert(siteurl);

$.ajax({
async:false,
url: siteurl + “/_api/web/lists/getbytitle(‘Editor List’)/items?$select=Title,First_x0020_Name,Last_x0020_Name&$filter=((First_x0020_Name eq ‘”+firstName.val()+”‘) and (Last_x0020_Name eq ‘”+LastName.val()+”‘))&$top=5000”,
method: “GET”,
headers: { “Accept”: “application/json; odata=verbose” },
success: function (data) {
alert(“function sucess”);
if (data.d.results.length > 0 ) {

isValid=1;

}

else

{
isValid=0;

}
},
error: function (data) {
alert(“Error: “+ data);
}
});

if (isValid==1)
{

alert(“Firt Name and Last Name should be unique”);
return false;
}

return true;
}

        </script>​​<br/>​​<br/>

 

Happy SharePointing folks 🙂

 

Leave a Reply

Your email address will not be published.