Explaining a small example why we should use validations over apex. The key benefit is we don’t have to write test class for it. Also if salesforce provide powerful tools like validations and workflows then why write APEX.
I was jumping here and there in my code to find places where I can re-factor it to reduce code lines, what I got is this.
public boolean validatePhone(account acc) 

 if (acc.Phone != null) 
 { 
  String phoneNumber = acc.Phone ; 
  Pattern phonePattern = Pattern.compile(‘\\D*?(\\d\\D*?){10}’); 
        Pattern numericPattern = Pattern.compile(‘[0-9]{10}’); 
        Matcher phoneMatcher = phonePattern.matcher(phoneNumber); 
             
  if(phoneNumber.length() == 10) 
  { 
   Matcher numericMatcher = numericPattern.matcher(phoneNumber); 
   if(numericMatcher.matches()) 
   { 
    return true; 
   } 
   else 
   { 
    return false; 
   } 
  } 
  else 
  { 
   return false ; 
  } 
 } 
}
A apex code which validates a phone number, I am posting with some alterations as removing some unwanted code so please don’t blame me if this code doesn’t work after copy and paste.
Why I have written this code? Because if any user entering value in phone field then I want them to enter value in particular format i.e. (XXX)XXX-XXXX and it should be of 10 digit.
Then I just gave a thought over using validations and came up with a solution, writing a validation on account :

IF( ISBLANK(Phone) , false , NOT(REGEX(Phone, “\\D*?(\\d\\D*?){10}”)) ) 
Now I don’t need to write any code and any test class for it. I know there are some flaws in it but what my point is how we can reduce the apex code. Now don’t just give a devil smile and start looking for the flaws.

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *

*