function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Trigger error using pattern.matches


I am trying to use the pattern.matches function on an apex trigger on our sandbox, what we are trying to do is update a record to Pending Validation based on whether a linked record meets the format required.

So on the trigger we have:


trigger Enrg_PendingValidation_Trigger on Registrations__c (Before Update, Before Insert){

Boolean validTelephone;
telephonePat='[0-9]{3} [0-9]{4} [0-9]{4}';

telephone = reg.Site__r.Site_Phone__c;
validTelephone= Pattern.matches(telephonePat,telephone);

if(reg.Site__r.Site_Phone__c != null && validTelephone!= true ){
               reg.Registration_Status__c='Pending Validation';                                   

This trigger saves ok on Salesforce but when I try to edit and save the registration I get the error message
Script-thrown exception: Class.System.Pattern.matcher

It appears that the issue is being caused by the line validTelephone= Pattern.matches(telephonePat,telephone); as when I comment this out I am able to save the record.

Can anyone help me on this?  I can't see what I am doing wrong here.

Thanks in advance.

James LoghryJames Loghry
Most likely, your regex is incorrect. It's looking for a number like 111 2222 4444.  Note there are spaces instead of hyphens and the second block  is 4 characters instead of 3.

Try a different regex, something like:
Please note that this is a very basic regex and  wont match on numbers with parenthesis around area codes or phone numbers with extensions, etc.

Hi James,

Thanks for the reply - unfortunately when I try that format the error message still appears.

The field I'm validating against is from a child record - would this matter?