Java Validate International Phone Numbers


Below is example of how to use Pattern and Matcher in Java, to validate international phone numbers.

package myjavaexample; 
 
import java.awt.Component; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 
import javax.swing.border.EmptyBorder; 
 
public class MyJavaExample extends JFrame 
{ 
    private JTextField textphone = new JTextField(25); 
    public void showFrame() 
    { 
        setTitle("JFrame Login Example"); 

        JPanel panel = new JPanel(); 
        panel.setBorder(new EmptyBorder(10, 10, 10, 10)); 
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 

        JLabel phonelabel = new JLabel("Phone"); 
        phonelabel.setAlignmentX(Component.CENTER_ALIGNMENT); 
        panel.add(phonelabel); 
        textphone.setAlignmentX(Component.CENTER_ALIGNMENT); 
        panel.add(textphone); 

        JButton btn = new JButton("Check"); 
        btn.addActionListener( 
            new ActionListener() { 
                public void actionPerformed(ActionEvent e) { 
                    isPhoneNumber(); 
                } 
            }); 
        btn.setAlignmentX(Component.CENTER_ALIGNMENT); 
        panel.add(btn); 

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setLocation(100,100); 
        setSize(300, 120); 
        add(panel); 
        setResizable(false); 
        setVisible(true); 
    } 

    public void isPhoneNumber() 
    { 
        if(textphone.getText().isEmpty())return; 
        Pattern pattern = Pattern.compile("^\\+(?:[0-9] ?){6,14}[0-9]$"); 
        Matcher matcher = pattern.matcher(textphone.getText()); 
        JOptionPane.showMessageDialog(this,textphone.getText()+" is Phone Number: "+matcher.matches()); 
    } 

    public static void main(String[] args) { 
        MyJavaExample main=new MyJavaExample(); 
        main.showFrame(); 
    } 
} 

Comments



Popular posts from this blog

Simple Java Code HTML Highlighter

How to Use Extends and Implements

Fibonacci Algorithm in Java Array