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.


public string validateAndFormatPhnNum(String phnNum){

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


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.


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.