How to Validate Phone Number format

33,695

Solution 1

Why not remove all non-digits and then count the digits left and put the plus back in later? This allows users the freedom to fill out their phone number anyway they want...

String PhoneNo = "+123-456 7890";
String Regex = "[^\\d]";
String PhoneDigits = PhoneNo.replaceAll(Regex, "");
if (PhoneDigits.length()!=10)  
{
    // error message
}
else
{
    PhoneNo = "+";
    PhoneNo = PhoneNo.concat(PhoneDigits); // adding the plus sign

    // validation successful  

}

If your app is intended for international use replace

if (!PhoneDigits.length()!=10) 

with

if(PhoneDigits.length() < 6 || PhoneDigits.length() > 13)

as Fatti Khan suggested.


To apply this in the code you posted at Android EditText Validation and Regex first include this method in your public class or the class containing onClick():

public boolean validateNumber(String S) {
    String Regex = "[^\\d]";
    String PhoneDigits = S.replaceAll(Regex, "");
    return (PhoneDigits.length()!=10);
}

And include this method in the CreateNewRider class:

protected String tidyNumber(String S) {
    String Regex = "[^\\d]";
    String PhoneDigits = S.replaceAll(Regex, "");
    String Plus = "+";
    return Plus.concat(PhoneDigits);
}

This is where the validation happens...

@Override
public void onClick(View view) {

    Boolean b = false;
    if(inputfullname.getText().toString().equals("")) b = true;

    else if(... // do this for all fields

    else if(inputmobileNo.getText().toString().equals("")) b=true;
    else if(inputemergencyContactNo.getText().toString().equals("")) b=true;
    else {
        if(validateNumber( inputmobileNo.getText().toString() ) 
            Toast.makeText(RiderProfile.this, "Invalid mobile number", Toast.LENGTH_SHORT).show();

        else if(validateNumber( inputemergencyContactNo.getText().toString() ) 
            Toast.makeText(RiderProfile.this, "Invalid emergency contact number", Toast.LENGTH_SHORT).show();
        else {
            // Validation succesful

            new CreateNewRider().execute();

        }   
    }
    if(b) Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}

And then use tidyNumber() in the CreateNewRider class:

    protected String doInBackground(String... args) {
        String fullname= inputfullname.getText().toString();
        String IC= inputIC.getText().toString();
        String mobileNo= tidyNumber( inputmobileNo.getText().toString() );
        String emergencyContactName= inputemergencyContactName.getText().toString() );
        String emergencyContactNo= tidyNumber( inputemergencyContactNo.getText().toString() );

        ...

Solution 2

Given the rules you specified:

upto length 13 and including character + infront.

(and also incorporating the min length of 10 in your code)

You're going to want a regex that looks like this:

^\+[0-9]{10,13}$

With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.

Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.

[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:

^[+][0-9]{10,13}$

[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:

^[+]?[0-9]{10,13}$

For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number . Also we can not check like mobile number must starts with 9 or 8 or anything..

For mobile number I used this this Function

private boolean isValidMobile(String phone2) 
{
    boolean check;
    if(phone2.length() < 6 || phone2.length() > 13)
    {
        check = false;
        txtPhone.setError("Not Valid Number");
    }
    else
    {
        check = true;
    }
    return check;
}

Solution 3

^[\\+]\\d{3}\\d{7}$

Use anchors to limit the match.

^ => start of match

$=> end of match

Share:
33,695
king yaya
Author by

king yaya

Updated on July 10, 2022

Comments

  • king yaya
    king yaya almost 2 years

    i am about to create a validation for phone number format..The format is 10 digit including the plus sign eg:+0133999504. Even though I have declare the pattern which is I try to disallow the "-" symbol or any other characters, but the validation is not working. Any other Idea or solution?

    1st I declared the string regex:
    
    String PhoneNo;
    String PhoneNo_PATTERN ="[\\+]\\d{3}\\d{7}";
    
    2nd I make a if..else statement:
     {
                        Pattern pattern = Pattern.compile(PhoneNo_PATTERN);
                        Matcher matcher = pattern.matcher(PhoneNo);
                        if (!matcher.matches()) 
                        {
                        inputemergencyContactNo.setError("Please enter Emergency Contact No");
                        }
                        else{
                        Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
                        }