Is there any way to override custom validation rules? I have created a validation rule that does not allows to change on my custom fields but I want to make an exception to that it should allows you to change using the apex code
or is there a way to disable validation rule before I update the object and enable back?


Yes, you can create a Hierarchical custom setting, and then set it in your code. Hierarchical custom setting values are available in validation rules. After you code had finished doing what it needs to do, you unset the setting.

Something like this:

1) Set up a hierarchical custom setting called "Validations", and add a checkbox field to it called "Disable My Validation Rule" (name these whatever you want). Make sure it's unchecked by default.

2) In your code, before you do any updates on records, set this custom setting:

/* apex  */
Validations__c validations = Validations__c.getOrgDefaults();
if (validations == null) {
    validations = new Validations__c();
validations.disable_my_validation_rule__c = true;
upsert validations;

// then do your processing
// once done, unset the setting

validations.disable_my_validation_rule__c = false;
update validations;

3) In your validation rule, add handling for this setting:

/* validation rule */
&& ( /* the rest of your validation criteria */ )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.