Custom validation for Text Fields

Topics: Customizing Orchard, Writing modules
Jul 22, 2013 at 5:41 PM
I have some content parts with attached text fields, I'd like to perform some validation on those fields beyond the simple Required option, for example: date (for birth date), phone number, ZIP code...

What would be the recommended way to do that? A set of custom fields? Adding some flavors (filters?) to the TextField just like markdown does?

Some of those fields are already live and have data so how could I keep their values, assuming they are valid, while enabling that new validation?

Jul 22, 2013 at 7:17 PM
If you run 1.x (1.7 RC), it could be a good case to use the new Script Validation part.

This a part added to the content with which you can specify a custom Validation using C# interpreted code, tokens and some methods or properties.
Jul 22, 2013 at 8:40 PM
Interesting, didn't know about this feature.

How would that work if my content item had fields coming from two different parts, and I assigned those fields to different groups according to the parts? The goal being to use the content manager's BuildEditor() method from within a controller and only show the fields attached to one content part.
Apr 4, 2014 at 2:03 PM
This is a really old post but throwing out an example for anyone else who might stumble upon this (or when I do in the future). Here is an example of how to use the Script Validation part:
bool authenticationRequired = ContentItem.ProductPart.AuthenticationRequired;
if (!authenticationRequired) {
     AddModelError("The company requires that all products have 'authentication required' checked. Please check then publish again.");
The trick is to keep everything dynamic as the scripting engine doesn't know about the models you have available. So for a part variable the dynamic expression is something like this:


For a field (assuming the field get's attached to the default part then the part is just the content type id) it should be something like this:


So it could be something like this (not tested)


Once you have your variables, you can use C# logic to implement and throw Model Errors as exampled above.