Today I’ve had a bit of a wrestle with list item validation in SharePoint 2010. Consider the following scenario:
We have a list for expenses, which includes a few fields for the cost of the expense. We may have a field for the cost of the goods, a field for the rate of tax (VAT, GST, or whatever it’s called in your country) and a field for the total cost including the tax. Obviously we don’t want our users to have to fill in all of those fields, since given either a base cost or total cost we can calculate the other using the tax rate. As such we need to check that the user has not left both fields blank.
Do it through the UI
So we deploy the list, we open the list settings in the UI, we choose ‘Validation Settings’ and put this in the formula:
=IF([Cost ex tax]="",IF([Total cost]="","Error",""),"")=""
In simple terms, if the cost excluding tax is empty and the total cost is empty then return “Error”, otherwise return blank. The validation result is true if the result returned from the IF is “”. Click Save, try it out, and sure enough it works!
Put it in your schema.xml
HOWEVER, we want to deploy this expenses solution to a load of different sites, so we want to put the validation rules into our schema.xml for the list definition. This is where the fun starts – in our <MetaData> element under our <List> element we can add a <Validation> element. The MSFT documentation, rather predictably, doesn’t give any useful information about this validation element. Through a bit of trial and error this is how it needs to be done:
<List>
<MetaData>
<Validation Message="You must complete at least one of 'Cost ex tax' or 'Total cost'">
=IF(CostExTax="", IF(TotalCost="", "Error", ""), "")=""
</Validation>
<ContentTypes>...</ContentTypes>
<Fields>...</Fields>
<Views>...</Views>
<Forms>...</Forms>
</MetaData>
</List>
Note: I have added white space around the validation formula to make this example more readable.
Things to note about this markup
- The validation element has a ‘Script’ attribute, that is used to specify javascript validation, NOT the validation formula
- The validation formula itself must be put in between <Validation> and </Validation>
- When you’re entering the formula through the UI you use the display name of the fields with brackets around it.
- When you’re entering the formula in the CAML you use the internal name of the fields with no brackets.
Hopefully this will save someone a bit of trial and error!