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.















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


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

  1. using (SPSite site = new SPSite("http://serverName:1111/sites/SPSiteDataQuery/ "))

  2. {

  3. using (SPWeb web = site.OpenWeb("Subsite1"))   

  4. {

  5. SPList list = web.Lists.TryGetList("Resume");

  6. if (list != null)        

  7. {

  8. SPFieldNumber fieldNumber = list.Fields.GetField("Years of experience") asSPFieldNumber;            

  9. fieldNumber.ValidationFormula = "=AND([Years of experience]>3,[Years of experience <6)";            

  10. fieldNumber.ValidationMessage = "Years of experience must be 3-6 years";            

  11. fieldNumber.Update();        

  12. }

  13. else        

  14. {

  15. Console.WriteLine("List does not exist in the site");        

  16. }

  17. Console.ReadLine();   

  18. }

  19. }



Using Power shell

  1. $siteURL="http://serverName:1111/sites/SPSiteDataQuery/"

  2. $listName="Resume"

  3. $fieldName="Years of experience"

  4. $validationFormula="=AND([Years of experience]>3,[Years of experience]<6)"

  5. $validationMessage="Years of experience must be 3-6 years"

  6. $site=Get-SPSite $siteURL

  7. $web=$site.OpenWeb("Subsite1")

  8. $list=$web.Lists.TryGetList($listName)

  9. if($list -ne $null)

  10. {   

  11. $fieldNumber=$list.Fields.GetField($fieldName)   

  12. $fieldNumber.ValidationFormula = $validationFormula   

  13. $fieldNumber.ValidationMessage = $validationMessage   

  14. $fieldNumber.Update()    

  15. write-host -f green "Custom Validation added to the "$fieldName " successfully"

  16. }

  17. else

  18. {   

  19. write-host -f yellow $listName "does not exist in the site"

  20. }


Recent Posts

See All