Hi
We all know USA phone number "(999) 999-9999" . How do we restrict user from invalid entry ?
We can create validation rule.
Error Condition Formula:- NOT(REGEX(Phone__c, "^\\(\\d{3}\\)\\s?\\d{3}-\\d{4}"))
Error Message:- US phone numbers should be in this format: (999) 999-9999.
if you want to add validation in controller, below is the method
public static boolean isValid(String phone){
String PhoneRegex = '^\\(\\d{3}\\)\\s?\\d{3}-\\d{4}';
Pattern MyPattern = Pattern.compile(PhoneRegex);
// then instantiate a new Matcher object “MyMatcher”
Matcher MyMatcher = MyPattern.matcher(phone);
if (!MyMatcher.matches()) {
return false;
}else{
return true;
}
}
public PageReference insertValue(){
if(Email_PhoneValidationController.isValid(testObj.Phone__c)){
insert testObj;
}
else{
testObj.Phone__c.addError('Invalid Phone Number format ...US phone numbers should be in this format: (999) 999-9999 ');
}
return null;
}
For the above regex "9999999999" & "999-999-9999" are invalid entry. This format "999-999-9999 " is aleo an USA format. If you want to make it valid entry then use below regex
NOT(REGEX(Phone, "\\D*?(\\d\\D*?){10}")) .
We all know USA phone number "(999) 999-9999" . How do we restrict user from invalid entry ?
We can create validation rule.
Error Condition Formula:- NOT(REGEX(Phone__c, "^\\(\\d{3}\\)\\s?\\d{3}-\\d{4}"))
Error Message:- US phone numbers should be in this format: (999) 999-9999.
if you want to add validation in controller, below is the method
public static boolean isValid(String phone){
String PhoneRegex = '^\\(\\d{3}\\)\\s?\\d{3}-\\d{4}';
Pattern MyPattern = Pattern.compile(PhoneRegex);
// then instantiate a new Matcher object “MyMatcher”
Matcher MyMatcher = MyPattern.matcher(phone);
if (!MyMatcher.matches()) {
return false;
}else{
return true;
}
}
public PageReference insertValue(){
if(Email_PhoneValidationController.isValid(testObj.Phone__c)){
insert testObj;
}
else{
testObj.Phone__c.addError('Invalid Phone Number format ...US phone numbers should be in this format: (999) 999-9999 ');
}
return null;
}
For the above regex "9999999999" & "999-999-9999" are invalid entry. This format "999-999-9999 " is aleo an USA format. If you want to make it valid entry then use below regex
NOT(REGEX(Phone, "\\D*?(\\d\\D*?){10}")) .
No comments:
Post a Comment