Mobile Number validation using Apex in Salesforce

Mobile Number validation using Apex in Salesforce

Using Pattern.matches() and RegEx, we can validate Phone Number or Mobile Number using Apex in Salesforce. In the following example, I have made sure the Account Phone number field contains only 10 digit number.

Sample Code:

trigger AccountTrigger on Account ( before insert, before update ) {

    for ( Account objAcc : trigger.new ) {
    
        if ( !Pattern.matches( '[0-9]{10}', objAcc.Phone ) ) {                         
            
            objAcc.Phone.addError( 'Incorrect Phone number' );
            
        }
    
    }

}

Update the RegEx used in the pattern() method as per your requirement.

Leave a Reply