Validation rule is a good friend of admins and end-users, to avoid bad data entry. The famous quote "An ounce of prevention is worth a pound of cure", is particularly true regarding data quality. Nobody wants the rubbish data in the production org to prevent them from getting valuable insights. However, similarly to all Salesforce features, there are always considerations.
A few common ones are already listed in the documentation, such as:
a specific setting for lead conventions (Require Validation for Converted Leads),
Web2Case and Web2Lead apply validation before creating records,
Mass Transfer tool, scheduled actions won't trigger validation,
Cannot refer to auto-number field, compound field, or dependent picklist, etc.
Recently in the practice, I found another interesting behavior.
I have 4 percentage fields to split a total amount of an opportunity, namely: Share1, Share2, Share3, Share4. To ensure they always add up to 100%, I built a validation rule.
1st version:
Share1__c + Share2__c + Share3__c + Share4__c !=1
Then I tested with all 4 numbers are entered, looked good. But when I left any of the fields blank, the error was gone!
Hmm, something went wrong with the empty field, which seems to bypass the validation.
The good side is that we have the formula BLANKVALUE() to rescue.
2nd version:
BLANKVALUE(Share1__c,0) + BLANKVALUE(Share2__c,0) + BLANKVALUE(Share3__c,0) + BLANKVALUE(Share4__c,0) ) !=1
Seemed to be working fine until I left all 4 fields blank. This could be OK for a use case that at least one of these fields is mandatory, but I want to allow users to leave all of them blank. So I need to add more logic for checking empty fields.
3rd version:
(BLANKVALUE(Share1__c,0) + BLANKVALUE(Share2__c,0) + BLANKVALUE(Share3__c,0) + BLANKVALUE(Share4__c,0) !=1)
&&
!(ISBLANK(Share1__c) && ISBLANK(Share2__c) && ISBLANK(Share3__c) && ISBLANK(Share4__c))
Some variation, if you always populate the Share1 first when you have value for these fields, the above rule can be simplified to this:
(Share1__c + BLANKVALUE(Share2__c,0) + BLANKVALUE(Share3__c,0) + BLANKVALUE(Share4__c,0) !=1)
&&
!(ISBLANK(Share1__c)
This may matter because the maximum length is 3900 characters, which is not easy to hit, but it's always to keep the formula as short as possible.
Another thing worth mentioning is when record types get involved, it's better to write inclusive rules instead of exclusive ones.
For example, the object has 3 record types TypeA, TypeB and TypeC, when you want to apply a rule for TypeA and TypeC, you can either use
RecordType.Name = 'TypeA' || RecordType.Name = 'TypeC'
or
RecordType.Name != 'TypeB'.
The latter one is even shorter, but I would recommend use the former. Why? It's for the future. If you use exclusive rules, when you add new record types that don't need validations, you have to go back and modify them. But if you use inclusive ones you don't need to worry about it.
No comments:
Post a Comment