Email and phone Number Validation in android
android
Solution
For Email Address Validation
private boolean isValidMail(String email) {
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
return Pattern.compile(EMAIL_STRING).matcher(email).matches();
}
OR
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
For Mobile Validation
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number. If your main target is your own country then you can match with the length. Assuming India has 10 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 two Function:
private boolean isValidMobile(String phone) {
if(!Pattern.matches("[a-zA-Z]+", phone)) {
return phone.length() > 6 && phone.length() <= 13;
}
return false;
}
OR
private boolean isValidMobile(String phone) {
return android.util.Patterns.PHONE.matcher(phone).matches();
}
Problem
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.