Skip to content

Validate US phone number and format with hyphens – Java

Here he would see on how to validate a US phone number on whether it is an integer, and on how to format it by adding hyphen without using loop.

Snippet

public string validateAndFormatPhnNum(String phnNum){
	phnNum=phnNum.replaceAll(“[a-zA-Z]”,””);
	phnNum=phnNum.replaceFirst(“(\\d{3})(\\d{3})(\\d+)”,”$1-$2-$3”);
}

Regular Expression (Regex) helps us in validation of a given input in both UI and backend.

replaceAll(“[a-zA-Z]”,””);

In the above line, we have used regex to avoid iterating each element of the given string, and avoid comparing each element with if/else for validation.

replaceFirst(“(\\d{3})(\\d{3})(\\d+)”,”$1-$2-$3”);

In the above line we have used regex formatting to add hyphens after every third position.

See also  Shuffle/Randomize an array in JavaScript using Knuth Fisher-Yates shuffle algorithm

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.