Salesforce 4-Digit Year Validation
I had an ask from the business for users to enter a year into a text field for a project I’m working on. The key challenge with using a text field for a 4-digit year value is that users can enter text too (it is a text field after all). This is easily overcome using this REGEX expression for a Salesforce 4-Digit Year validation….
NOT(
AND(
REGEX( Year__c, "^([2][0-9][0-9][0-9])$" ),
ABS( VALUE( Year__c ) - YEAR( TODAY() ) ) < 2
)
)
The REGEX( Year__c, “^([2][0–9][0–9][0–9])$” ) expression only allows for years greater than or equal to 2000. If you want it to work for 20th century years, change “[2]” to “[1]”.
The second line of the rule checks whether the year entered is within one year from today’s date. This helps when users fat-finger their data entry. Extend that to suit your needs. You could also swap out “TODAY()” for an actual date field. The “ABS()” function makes the result a positive integer no matter which year is earlier so we always get the result we want.
To use the validation rule…
- Create a new Text field named “Year” limited to 4 characters. The character limit is important for obvious reasons.
- Create new validation on “Year” field, and paste the formula from above and adjust as necessary.
- Be sure your validation rule is Active!
The “NOT” wrapping function ensures the test is negative and causes the validation to fire. Whenever I can, I’ll write a positive formula for field validations, and then wrap it in a NOT function to make it false.
What validation rules do you like to use for common problems like these?