Search code examples
validationtriggerssalesforceapex-code

How do I validate a field type in a trigger?


I have a trigger which fires on Lead (after update). We have an object called Finance which stores some financial information about each lead. When the trigger fires, it pushes any updates to certain fields into a finance record. What I have written works great, unless a user decides to input an invalid email, or the record owner is inactive. An APEX error is thrown, which to most users looks like gibberish and is a little scary.

What I would like to do is check in my trigger whether or not the email is valid so that users don't receive a confusing error. How can I go about checking whether a field's content is a valid type? I would like to stay away from using some sort of regex, because there are a couple other fields that I would like to apply this method to, and I'd rather not maintain a list of regex.

Any ideas?


Solution

  • You could catch the validation error in your trigger:

    try {
        upsert financeRecord;
    } catch (Exception e) {
        // do whatever you'd like to on an exception here
    }