[android] Email and phone Number Validation in android

I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.

Here is my code:

private boolean validate() {

    String MobilePattern = "[0-9]{10}";
    //String email1 = email.getText().toString().trim();
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

    if (name.length() > 25) {

        Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
        return true;

    } else if (name.length() == 0 || number.length() == 0 || email.length() == 
             0 || subject.length() == 0 || message.length() == 0) {

        Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
        return false;

    } else if (email.getText().toString().matches(emailPattern)) { 

        //Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
        return true;

    } else if(!email.getText().toString().matches(emailPattern)) { 

        Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
        return false;

    } else if(number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
        return true;

    } else if(!number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
        return false;
    }

    return false;
}

I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.

This question is related to android

The answer is


Try this

public class Validation {

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
        return false;
        } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    } 

    public static final boolean isValidPhoneNumber(CharSequence target) {
        if (target.length()!=10) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }
    }

}

//validation class

public class EditTextValidation {

public static boolean isValidText(CharSequence target) {
    return target != null && target.length() != 0;
}

public static boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

public static boolean isValidPhoneNumber(CharSequence target) {
    if (target.length() != 10) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}

//activity or fragment

    val userName = registerNameET.text?.trim().toString()
    val mobileNo = registerMobileET.text?.trim().toString()
    val emailID = registerEmailIDET.text?.trim().toString()

    when {
        !EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
        !EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
            "Please provide email"
        !EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
            "Please provide mobile number"
        else -> {
            showToast("Hello World")
        }
    }

**Hope it will work for you... It is a working example.


public boolean checkForEmail() {
        Context c;
        EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
        String mStrEmail = mEtEmail.getText().toString();
        if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
            return true;
        }
        Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
        return false;
    }


    public boolean checkForMobile() {
        Context c;
        EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
        String mStrMobile = mEtMobile.getText().toString();
        if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
            return true;
        }
        Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
        return false;
    }

XML

<android.support.v7.widget.AppCompatEditText
    android:id="@+id/et_email_contact"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLines="1"
    android:hint="Enter Email or Phone Number"/>

Java

private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;     

et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String regex = "^[+]?[0-9]{10,13}$";
        String emailContact = s.toString();
        if (TextUtils.isEmpty(emailContact)) {
            Log.e("Validation", "Enter Mobile No or Email");
        } else {
            if (emailContact.matches(regex)) {
                Log.e("Validation", "Valid Mobile No");
                validPhone = true;
                validEmail = false;
            } else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
                Log.e("Validation", "Valid Email Address");
                validPhone = false;
                validEmail = true;
            } else {
                validPhone = false;
                validEmail = false;
                Log.e("Validation", "Invalid Mobile No or Email");
            }
        }
    }
});

if (validPhone || validEmail) {
    Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}

try this:

extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));

private boolean validateMobile()    {   

    String mobile =extMobileNo.getText().toString().trim();
    if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )

    {
            inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
        requestFocus(extMobileNo);
        return false;
    }

    else {
        inputLayoutMobile.setErrorEnabled(false);
    }

    return true;
}

private static boolean isValidMobile(String mobile)
{
    return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}

For check email and phone number you need to do that

public static boolean isValidMobile(String phone) {
    boolean check = false;
    if (!Pattern.matches("[a-zA-Z]+", phone)) {
        if (phone.length() < 9 || phone.length() > 13) {
            // if(phone.length() != 10) {
            check = false;
            // txtPhone.setError("Not Valid Number");
        } else {
            check = android.util.Patterns.PHONE.matcher(phone).matches();
        }
    } else {
        check = false;
    }
    return check;
}

public static boolean isEmailValid(String email) {
    boolean check;
    Pattern p;
    Matcher m;

    String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    p = Pattern.compile(EMAIL_STRING);

    m = p.matcher(email);
    check = m.matches();

    return check;
}



String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else{// Not valid email or phone number

}


Use Pattern package in Android to match the input validation for email and phone

Do like

android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();

Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.

private boolean isValidEmail(CharSequence email) {
    if (!TextUtils.isEmpty(email)) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }
    return false;
}

private boolean isValidPhoneNumber(CharSequence phoneNumber) {
    if (!TextUtils.isEmpty(phoneNumber)) {
        return Patterns.PHONE.matcher(phoneNumber).matches();
    }
    return false;
}

in Kotlin you can use Extension function to validate input

// for Email validation

 fun String.isValidEmail(): Boolean =
        this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

// for Phone validation

fun String.isValidMobile(phone: String): Boolean {
    return Patterns.PHONE.matcher(phone).matches()
}

I am always using this methode for Email Validation:

public boolean checkForEmail(Context c, EditText edit) {
    String str = edit.getText().toString();
    if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
        return true;
    }
    Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
    return false;
}

He want an elegant and proper solution try this small regex pattern matcher.

This is specifically for India.(First digit can't be zero and and then can be any 9 digits) return mobile.matches("[1-9][0-9]{9}");

Pattern Breakdown:-

[1-9] matches first digit and checks if number(integer) lies between(inclusive) 1 to 9 [0-9]{9} matches the same thing but {9} tells the pattern that it has to check for upcoming all 9 digits.

Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.