+ Start a Discussion

Complex Validation Rules


Is it possible to throw a new System.DmlException from a trigger. I need to create a complex validation rule that can't be done with the normally defined custom validation rules.

Thanks for any help!

Message Edited by Scott.M on 09-17-2008 07:41 AM
I just read that system exceptions cannot be explicitly thrown so the answer is no. Throwing a custom exception gets the desired effect but the message is a bit ugly is there a way to display the message in a cleaner way, here's my code.

trigger validateContract on Contract (before insert) {

    public class CustomDmlException extends Exception {}
    for(Contract c: Trigger.new) {
        Contract[] contracts = [SELECT id FROM Contract WHERE CustomObject__c = :c.CustomObject__c AND ((StartDate >= :c.StartDate AND StartDate <= :c.EndDate) OR (EndDate >=: c.StartDate AND EndDate <=: c.EndDate))];
        if(contracts.size() > 0) {
            throw new CustomDmlException('The selected custom object has a conflict in the given date range');



I figured out a work around for doing complex validations.

1. Create a hidden field on the object
2. Create an on before update and insert trigger that executes the validation and sets the hidden field to some value
3. Write a validation rule that checks if the hidden field and displays the desired message on some condition

That's it, now you can get as funky with your validation as you like :)

Message Edited by Scott.M on 09-17-2008 07:41 AM
Love messages like this where someone is left to their own, works out a method and then teaches me something useful.

Kind of like a guy with an arm under a rock, shouting for help, then resorting to chewing his own arm of, then writing books on best approach for it.