Phone number validation Android
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}$
Android: Validate Phone Number Length by COUNTRY
Adding to @Zain 's answer.
String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
// This will check if the phone number is real and its length is valid.
boolean isPossible = phoneUtil.isPossibleNumber(swissNumberProto);
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
Email and phone Number Validation in android
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();
}
How to do Phone number validation in Android?
Try this Method:
private boolean isValidPhoneNumber(String phone) {
if (!phone.trim().equals("") && phone.length() > 10) {
return Patterns.PHONE.matcher(phone).matches();
}
return false;
}
How to validate phone number and amount
Call this function from TextWatcher (For NTC Prepaid validation)
"^(984|986)\d{7}$" this means phone number starts with 984 or 986 and after that there is 7 digits i.e. total 10 digits
phoneNumber.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) {
if(!isValidNumber(s.toString())){
isnumbervalid=false;
phoneNumber.setTextColor(Color.parseColor("#F44336"));
}else {
isnumbervalid=true;
phoneNumber.setTextColor(Color.parseColor("#000000"));
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
private boolean isValidNumber(String phonenumber) {
String PHONE_PATTERN = "^(984|986)\\d{7}$";
Pattern pattern = Pattern.compile(PHONE_PATTERN);
Matcher matcher = pattern.matcher(phonenumber);
return matcher.matches();
}
How to check and validate , given editext is phone number or mobile number?
Try this
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String data = editemail.getText().toString().trim();
String pass = edtPass.getText().toString().trim();
boolean flag = false;
if (TextUtils.isEmpty(pass)) {
edtPass.setError("Enter password");
//edtPass.requestFocus();
}else {
}
if (TextUtils.isEmpty(data)) {
editemail.setError("Enter Data");
} else {
if (data.matches("[0-9]+")) {
if (data.length() < 10 && data.length() > 10) {
editemail.setError("Please Enter valid phone number");
editemail.requestFocus();
} else {
flag = true;
}
} else {
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(data).matches()) {
editemail.setError("Please Enter valid email");
editemail.requestFocus();
}else {
flag = true;
}
}
}
if(!TextUtils.isEmpty(pass)&&flag){
Toast.makeText(MainActivity.this, "pass", Toast.LENGTH_SHORT).show();
}
}
});
How to Validate Phone Number format
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() );
...
How to check if phone number is valid in android
PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber) is not a proper way to check phone number is valid or not. I found a better solution for this and it is working for me.
First we need to add below library in the gradle file.
Library: com.googlecode.libphonenumber:libphonenumber:8.4.2
We need to pass mobile number and country code to the below function and it will return true if the phone number is valid.
public static PhoneValidateResponse isPhoneNumberValidate(String mobNumber, String countryCode) {
PhoneValidateResponse phoneNumberValidate = new PhoneValidateResponse();
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber = null;
boolean finalNumber = false;
PhoneNumberUtil.PhoneNumberType isMobile = null;
boolean isValid = false;
try {
String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
phoneNumber = phoneNumberUtil.parse(mobNumber, isoCode);
isValid = phoneNumberUtil.isValidNumber(phoneNumber);
isMobile = phoneNumberUtil.getNumberType(phoneNumber);
phoneNumberValidate.setCode(String.valueOf(phoneNumber.getCountryCode()));
phoneNumberValidate.setPhone(String.valueOf(phoneNumber.getNationalNumber()));
phoneNumberValidate.setValid(false);
} catch (NumberParseException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (isValid && (PhoneNumberUtil.PhoneNumberType.MOBILE == isMobile ||
PhoneNumberUtil.PhoneNumberType.FIXED_LINE_OR_MOBILE == isMobile)) {
finalNumber = true;
phoneNumberValidate.setValid(true);
}
return phoneNumberValidate;
}
Model class PhoneValidateResponse.
public class PhoneValidateResponse {
private String Phone;
private String Code;
private boolean isValid;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getCode() {
return Code;
}
public void setCode(String code) {
Code = code;
}
public boolean isValid() {
return isValid;
}
public void setValid(boolean valid) {
isValid = valid;
}
}
As per my code if isValid() of PhoneValidateResponse method returns true then the given phone number and country code are matched.
validate phone number android
Use this pattern:
^\s*(?:(?:\+?46)|0)(?:\d){9,10}\s*$
^
at start and $
at end ensure pattern matches the whole input
\s*
trim any space or tab\d
capture any digit
(?:\d){9,10}
means the pattern (?:\d)
should be repeated 9 to 10 times.
``
Pattern start with (+46
or 46
) or 0
follow by 9 or 10 digit.
If it could contain -
or space between numbers, use this:
^\s*(?:(?:\+?46)|0)(?:[- ]*\d){9,10}\s*$
You could test regex here
Related Topics
Help with a Custom View Attributes Inside a Android Library Project
Change Progressbar Color Through Code Only in Android
Google Maps Android API V2 - Sample Code Crashes
Does Android Service Run from a Separated Thread Instead of UI
Invalid Heap Address and Fatal Signal 11
How to Use Standard Attribute Android:Text in My Custom View
How to Import Eclipse Library Project from Github to Android Studio Project
Import an Eclipse Android Project with Version Control System into Android Studio
Pdf Library for Android - Pdfbox
Easier Way to Get View's Id (String) by Its Id (Int)
List View Item Swipe Left and Swipe Right
How to Replace The Activity's Fragment from The Fragment Itself
Designing Android Apps for Tablets
Trying to Port Apache Poi to Android
Inconsistency Detected in Recyclerview, How to Change Contents of Recyclerview While Scrolling
How to Set a Fragment Tag by Code