Scenario: Building custom validations
Sometimes, you need to enforce specific business rules that cannot be accomplished using the standard validation rules in Salesforce. In such cases, you can use Apex to build custom validations.
For example, let's say you want to enforce the following business rule: If a Contact record has the value "High" in the Priority field, the Lead Source field cannot be blank.
Here's the code to implement this validation:
In this code, the validateContact method takes a Contact record as an input, and checks if the value of the Priority field is "High" and the Lead Source field is blank.
If both conditions are true, it adds an error message to the Lead Source field, which will prevent the record from being saved.
To use this validation, you would add a trigger on the Contact object that calls the validateContact method before insert or before update.
Here's an example trigger:
This trigger will call the validateContact method for each Contact record being inserted or updated, and enforce the custom validation.
0 Comments