-1

I would like to implement the a phone number validation to a field in my application in java such that the field allows only the phone number in the format "+543353453".

I would like to do it using Regular expressions but Regex are a bit confusing to me.

The below code does not work.

public static void main(String args[])
{    
    String a[]=new String[]{"+90030","3434","+403403"};

    String regEx="\\+\\d{9}";
    pattern = Pattern.compile(regEx);

    for(int i=0;i<a.length;i++)
    {
        boolean matches=pattern.equals(a[i]);
        if(pattern.equals(a[i]))
            System.out.println("Phone number is valid"+a[i]);   
        else
            System.out.println("Phone number is invalid"+a[i]);
        } 
    }
}
Backs
  • 24,430
  • 5
  • 58
  • 85
Sawyer
  • 423
  • 1
  • 7
  • 23

1 Answers1

1

Use this code:

    public static void main(String args[]) {
    String a[] = new String[] { "+90030", "3434", "+403403", "+477777777" };

    String regEx = "\\+\\d{9}";
    Pattern pattern = Pattern.compile(regEx);

    for (int i = 0; i < a.length; i++) {
        boolean matches = pattern.matcher(a[i]).matches();
        if (matches)
            System.out.println("Phone number is valid" + a[i]);
        else
            System.out.println("Phone number is invalid" + a[i]);
    }
}

And spend some time reading the doc, you were comparing a pattern and a String, they could not be equal. And finally, in your test case, add at least a case which passes the validation.

StephaneM
  • 4,779
  • 1
  • 16
  • 33