Find your content:

Search form

You are here

Regex NullObject in Trigger if run from Dataloader else works fine

 
Share

Fellow developers,

I have a call to an email validation function in my before insert in my trigger, which basically puts the email blank if its not valid (according to the regex)

public static String validEmailOrBlank(String email)
{
    String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
    Pattern emailPattern = Pattern.compile(emailRegex);

    Matcher emailMatcher = emailPattern.matcher(email);

    if (!emailMatcher.matches()) {
        email = '';
    }
    return email;
}

This works fine if I manually create a record (in this case it is a custom object) which empties the email field (which is just a regular text fieldtype, no email field type, this is intentional) However, when I use the dataloader to mass import records, I get nullpointers

... execution of BeforeInsert
caused by: System.NullPointerException: Script-thrown exception
(System Code)
Class.Utilities.validEmailOrBlank: line 9, column 1
...

line 9 in this case is:

Matcher emailMatcher = emailPattern.matcher(email);

Anyone have an idea?


Attribution to: pjcarly

Possible Suggestion/Solution #1

The csv file you're loading potentially contains null email addresses. (I was able to reproduce the NullPointerException by passing a null string to your method in Execute Anonymous, so a fair assumption I would think)

Your code, as it stands, would throw a null pointer exception if the email field is null. So add a not null check for email before attempting to compile a pattern match

public static String validEmailOrBlank(String email)
{
if (email != null) { //NOT NULL CHECK
    String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
    Pattern emailPattern = Pattern.compile(emailRegex);

    Matcher emailMatcher = emailPattern.matcher(email);

    if (!emailMatcher.matches()) {
        email = '';
    }
   }
    return email;
}

Just tried this and it works alright.


Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3764

My Block Status

My Block Content