Validating phone numbers is a frequent need in Salesforce development, whether you’re dealing with Leads, Contacts, or custom objects. Ensuring that only valid phone numbers are stored in your org improves data quality and enhances user experience. In this blog, you’ll learn how to create a reusable Apex utility class for phone number validation, see how to use it, and understand why this logic is a best practice.
- Data Quality: Prevents storage of incorrect or malformed phone numbers.
- User Experience: Provides immediate feedback on invalid entries.
- Downstream Reliability: Reduces issues with integrations, SMS, or call services.
Here’s a simple Apex utility class that uses regular expressions (regex) to check if a phone number conforms to standard formats (including US and basic international).
public class PhoneUtils {
// Method to validate a phone number format (simple international and US formats)
public static Boolean isValidPhone(String phone) {
if (String.isBlank(phone)) return false;
// Regex for phone validation (matches numbers, spaces, dashes, parentheses, plus sign)
Pattern p = Pattern.compile('^(\\+\\d{1,3}[- ]?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$');
Matcher m = p.matcher(phone);
return m.matches();
}
}
This utility can be called from triggers, classes, or Lightning components—anywhere you need to validate a phone number.
Boolean isPhoneOk = PhoneUtils.isValidPhone('+1 (555) 123-4567');
System.debug(isPhoneOk); // Returns true if valid, false otherwise
- Reusable: Centralized logic can be used throughout your org.
- Bulk-Safe: No database operations, so it works well with bulk data.
- Easy to Update: Modify the regex in one place if your requirements change.
- Efficient: Lightweight and fast, with no impact on governor limits.
Apex utility classes like this phone validator help keep your Salesforce org clean, consistent, and maintainable. By validating user input at the code level, you catch data issues early and provide a better experience for users and downstream processes.
Happy coding with Salesforce Apex!
Post a Comment