Home > Blockchain >  How to validate phone number using spring boot?
How to validate phone number using spring boot?

Time:03-29

how to validate virtual number/phone number in java?

Virtual number can be 12 characters long and format should be 90507167819. I want to check for length and alphanumeric character. virtualNumber is string and example : 905523458295

CodePudding user response:

you can create a custom validator to accommodate your phone number rules, refer to this article where you can learn how to create custom validators https://www.baeldung.com/spring-mvc-custom-validator.

You can use regex also to make sure the input matches what you expect.

CodePudding user response:

The question is a bit vague but I will cover various aspects of a phone number validation

The first level of validation is a simple phone number format validation. This can be performed by a regular expression match.

String pattern = "\\d{10}|(?:\\d{3}-){2}\\d{4}|\\(\\d{3}\\)\\d{3}-?\\d{4}";
if (inputString.matches(pattern)) {     
    System.out.println("Valid"); 
} else {     
    System.out.println("Invalid"); 
} 

refer this thread for more on regular expression matching.

Next is a locale based validation of the number based on country code, starting digits and number of digits as well as various formatting styles for numbers. The best solution for this is to use Google PhoneUtils. They do an excellent job of keeping up with the ever changing number formats in various countries/regions. Import the google phone utils library with maven or gradle into your project.

<!-- https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber -->
<dependency>
    <groupId>com.googlecode.libphonenumber</groupId>
    <artifactId>libphonenumber</artifactId>
    <version>8.12.45</version>
</dependency>

Usage as below

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: "   e.toString());
}

More details about the project here

Finally, the last method of a phone number validation is to actually place an call to the number. This requires a more elaborate integration with a VoIP automation provider such as Twilio. Twilio provides APIs for phone validation. You can call these APIs from your java code and pass a phone number and handle the various response codes. More details here. This is a paid solution https://www.twilio.com/docs/lookup/tutorials/validation-and-formatting

  • Related