How to validate phone number in Java (regular expression)
Regular expression pattern in Java always is the best method to validate an user’s phone number. Here i provide a regex pattern to determines if the phone number is in correct format, the pattern force starting with 3 digits follow by a “-” and 7 digits at the end.
\\d{3}-\\d{7} Explanation
\\d = only digit allow
{3} = length
All phone numbers must in “xxx-xxxxxxx” format. For example
1) 012-6677889 – Passed
2) 01216677889 – Failed , “-” missing
3) A12-6677889 – Failed , only digit allow
4) 012-66778899 – Failed, only 7 digits at the end
Full source code of phone number validation in Java
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidatePhoneNumber { public static void main(String[] argv) { String sPhoneNumber = "605-8889999"; //String sPhoneNumber = "605-88899991"; //String sPhoneNumber = "605-888999A"; Pattern pattern = Pattern.compile("\\d{3}-\\d{7}"); Matcher matcher = pattern.matcher(sPhoneNumber); if (matcher.matches()) { System.out.println("Phone Number Valid"); } else { System.out.println("Phone Number must be in the form XXX-XXXXXXX"); } } }







Pls give me some idea 2 write telephone line checking code in java
I’m new to springs can someone help me validate a contact number in Spring .
Thanks.
hi i want to know how should be the pattern if i want the user to enter a number begining with 21 or 27 followed by 6 numbers
please help me
Thanks
[...] Code: http://www.mkyong.com/java/how-do-validate-phone-number-in-java-regular-expression/ [...]
Unfortunately this works for US based numbers only. Not everyone in the world has the same style phone number.
Try understand the concept, and you can customize it to any use case.
I created a phone number pattern a little different. I’m trying to verify it’s validity. ^(\d?\d?\d?\d)?(\d{3})(\d{7})$
First I have a method that strips non-numbers out of the string because there are all kinds of formats people use including parenthesis dashes, periods, etc.
My regular expression matches first 7 digits. It’s in a group so I can pull it out if I want. Next I match 3 digits for the area code. Again it is grouped so that I can pull it out and use it or store it however I want it. Then I have an optional group for the country code. If I do have the group, then I have at least one digit with 3 more optional digits.
Any comments suggestions?
I’ve written some basic unit tests, but I might not be testing some edge cases.
your pattern is great, pattern contains unlimited possibilities, and just make sure you make a detail unit test to cover all your use case
hi, i want to check that no. must be of 10 digits with first digit non-zero, how to write RE for this ?