How to do custom validation for site column in SharePoint


In this article we will be seeing how to do custom validation for site column in SharePoint using power shell and SharePoint object model.

I have created a list "Resume" where the users can upload the resume and will be filling some basic details. I have four columns:

  • Name

  • Email ID

  • Mobile No

  • Years of experience

I am going to do some custom validation for "Years of experience" column. Only users who have experience of 3-6 years can upload the resume.

I have created a custom validation as shown in the following which has the Formula and User message (where you can display some custom error message).

Go to SharePoint site -> List -> List Settings -> Columns -> click on the column to edit.

CustomValidation1.gif

If Years of experience value is not between 3-6 years it will throw a custom error message as shown in the following.

CustomValidation2.gif

Using SharePoint object model you can achieve the same thing as shown in the following.

using (SPSite site = new SPSite("http://serverName:1111/sites/SPSiteDataQuery/ "))
{
    using (SPWeb web = site.OpenWeb("Subsite1"))
    {
         SPList list = web.Lists.TryGetList("Resume");
         if (list != null)
         {
             SPFieldNumber fieldNumber = list.Fields.GetField("Years of experience") as SPFieldNumber;
             fieldNumber.ValidationFormula = "=AND([Years of experience]>3,[Years of experience]<6)";
             fieldNumber.ValidationMessage = "Years of experience must be 3-6 years";
             fieldNumber.Update();
         }
         else
         {
             Console.WriteLine("List does not exist in the site");
         }
             Console.ReadLine();
    }
}

Using Power shell

$siteURL="http://serverName:1111/sites/SPSiteDataQuery/"
$listName="Resume"
$fieldName="Years of experience"
$validationFormula="=AND([Years of experience]>3,[Years of experience]<6)"
$validationMessage="Years of experience must be 3-6 years"
$site=Get-SPSite $siteURL
$web=$site.OpenWeb("Subsite1")
$list=$web.Lists.TryGetList($listName)
if($list -ne $null)
{
    $fieldNumber=$list.Fields.GetField($fieldName)
    $fieldNumber.ValidationFormula = $validationFormula
    $fieldNumber.ValidationMessage = $validationMessage
    $fieldNumber.Update()
    write-host -f green "Custom Validation added to the "$fieldName " successfully"
}
else
{
    write-host -f yellow $listName "does not exist in the site"
}

CustomValidation3.gif