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:
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.
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") asSPFieldNumber;
fieldNumber.ValidationFormula = "=AND([Years of experience]>3,[Years of experience <6)";
fieldNumber.ValidationMessage = "Years of experience must be 3-6 years";
Console.WriteLine("List does not exist in the site");
Using Power shell
$fieldName="Years of experience"
$validationFormula="=AND([Years of experience]>3,[Years of experience]<6)"
$validationMessage="Years of experience must be 3-6 years"
if($list -ne $null)
$fieldNumber.ValidationFormula = $validationFormula
$fieldNumber.ValidationMessage = $validationMessage
write-host -f green "Custom Validation added to the "$fieldName " successfully"
write-host -f yellow $listName "does not exist in the site"