+ Start a Discussion

Any way to reference Apex constants (or other types of constants) from validation formulas

Some of our business objects have fields that serve a common purpose, and we have validation rules for those fields that check their values using regular expressions.  The regular expressions aren't terribly complex, but I hate having the same expression repeated in every instance of the validation rule.  What I'd really like to be able to do is something like:


NOT(REGEX(MyField__c, ValidationConstants.COMMON_FIELD_PATTERN))


However, as far as I know there's no way to access string constants defined in Apex from formula expressions.  I could do this with pre-DML triggers, but then I'd have to register the triggers on all objects with fields that need to be validated this way.  I'm hoping that someone has run into this and has a good idea of how I can do this.


Oh, and one thought was to use VLOOKUP() and create a custom object where the instances are the patterns, then do something like:


NOT(REGEX(MyField__c, VLOOKUP($ObjectType.ValidationConstants__c.Fields.Value__c, $ObjectType.ValidationConstants__c.Fields.Name, "COMMON_FIELD_PATTERN"))


and I imagine that would work, but man...it just seems like the tail wagging the dog to have centralized definitions for commonly repeated values!


Thanks in advance for any tips!



Have you considered using Custom Settings of type Hierarchy? You can reference the value of the custom setting field value in validation rule formulas. Here are a few links about custom settings and accessing custom settings via formulas.

https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_about.htm&language=en_US (https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_about.htm&language=en_US)

​https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_accessing.htm&language=en_US (https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_accessing.htm&language=en_US)