Flutter - Validate a phone number using Regex - android

In my Flutter mobile app, I am trying to validate a phone number using regex. Below are the conditions.
Phone numbers must contain 10 digits.
In case country code us used, it can be 12 digits. (example country codes: +12, 012)
No space or no characters allowed between digits
In simple terms, here is are the only "valid" phone numbers
0776233475, +94776233475, 094776233475
Below is what I tried, but it do not work.
String _phoneNumberValidator(String value) {
Pattern pattern =
r'/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value))
return 'Enter Valid Phone Number';
else
return null;
}
How can I solve this?

You could make the first part optional matching either a + or 0 followed by a 9. Then match 10 digits:
^(?:[+0]9)?[0-9]{10}$
^ Start of string
(?:[+0]9)? Optionally match a + or 0 followed by 9
[0-9]{10} Match 10 digits
$ End of string
Regex demo

Validation using Regex:
String validateMobile(String value) {
String pattern = r'(^(?:[+0]9)?[0-9]{10,12}$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return 'Please enter mobile number';
}
else if (!regExp.hasMatch(value)) {
return 'Please enter valid mobile number';
}
return null;
}

#override
String validator(String value) {
if (value.isEmpty) {
return 'Mobile can\'t be empty';
} else if (value.isNotEmpty) {
//bool mobileValid = RegExp(r"^(?:\+88||01)?(?:\d{10}|\d{13})$").hasMatch(value);
bool mobileValid =
RegExp(r'^(?:\+?88|0088)?01[13-9]\d{8}$').hasMatch(value);
return mobileValid ? null : "Invalid mobile";
}
}

I used the RegExp provided by #Dharmesh
This is how you can do it with null safety.
bool isPhoneNoValid(String? phoneNo) {
if (phoneNo == null) return false;
final regExp = RegExp(r'(^(?:[+0]9)?[0-9]{10,12}$)');
return regExp.hasMatch(phoneNo);
}
Usage:
bool isValid = isPhoneNoValid('your_phone_no');

String phoneNumberValidator(String value) {
Pattern pattern =
r'\+994\s+\([0-9]{2}\)\s+[0-9]{3}\s+[0-9]{2}\s+[0-9]{2}';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value))
return 'Enter Valid Phone Number';
else
return null;
}

Related

Password Patteren does not matched with the Matcher class

My Password should be Like :
"Password should contain at least one uppercase letter, one lowercase letter, one digit and one special character with minimum eight character length"
The Pattern I have used is : ^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$#$#!%*?&])[A-Za-z\\d$#$#!%*?&]{8,}
So, I have created a function as below in my Constant.java file :
public static Boolean passwordMatcher(TextInputLayout edtText,String string) {
Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)(?=.*[$#$#!%*?&])[A-Za-z\\\\d$#$#!%*?&]{8,}");
Matcher matcher = pattern.matcher(edtText.getEditText().getText().toString());
boolean isMatched = matcher.matches();
if (isMatched) {
return true;
}
if (!isMatched) {
edtText.setErrorEnabled(true);
edtText.setError("" + string);
edtText.setFocusable(true);
return false;
}
return true;
}
and in my MainActivity.java file I have checked for validation as below :
if (!Constant.passwordMatcher(edtPassword, mContext.getResources().getString(R.string.error_activity_signup_password_invalid))) {
return;
}
But, I am not getting success even if I have tried : 'Jaimin123#' as a my password.
Always getting error set in my TextInputLayout.
What might be the issue ?
Thanks.
Try using below regex for password match.
^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$
This regex will check for below rules:
At least one upper case letter
At least one lower case letter
At least one digit
At least one special character
Minimum 8 in length
Try this
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$##!%*?&]).{8,}$
If you don't want white space in password include (?=\S+$) also
Try this code:
public void checkPattern(String password) {
Pattern pattern = Pattern.compile("(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\\W).{8,}");
Matcher matcher = pattern.matcher(password);
boolean isMatched = matcher.matches();
System.out.println(isMatched);
}
Try
public boolean matchesPattern(String password) {
Pattern pattern = Pattern.compile("^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$");
Matcher matcher = pattern.matcher(password);
return matcher.matches();
}

How to Validate Phone Number format

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();
}
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() );
...
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;
}
^[\\+]\\d{3}\\d{7}$
Use anchors to limit the match.
^ => start of match
$=> end of match
To validate India's mobile number.
Your edit text input
edt_mobile.text.toString().trim()
Number validation method
fun isValidMobile(phone: String): Boolean {
return phone.matches(Constants.REGEX_MOBILE.toRegex()) && phone.trim().length == 10
}
Regression expression
const val REGEX_MOBILE = "^[6-9]{1}[0-9]{9}\$"

Email address validation in Android [duplicate]

What's a good technique for validating an e-mail address (e.g. from a user input field) in Android? org.apache.commons.validator.routines.EmailValidator doesn't seem to be available. Are there any other libraries doing this which are included in Android already or would I have to use RegExp?
Another option is the built in Patterns starting with API Level 8:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Patterns viewable source
OR
One line solution from #AdamvandenHoven:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
Next pattern is used in K-9 mail:
public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
You can use function
private boolean checkEmail(String email) {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
Since API 8 (android 2.2) there is a pattern: android.util.Patterns.EMAIL_ADDRESS
http://developer.android.com/reference/android/util/Patterns.html
So you can use it to validate yourEmailString:
private boolean isValidEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
returns true if the email is valid
UPD:
This pattern source code is:
public static final Pattern EMAIL_ADDRESS
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
refer to: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/util/Patterns.java
So you can build it yourself for compatibility with API < 8.
We have a simple Email pattern matcher now.
Java:
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Kotlin Function:
private fun isValidEmail(email: String): Boolean {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Kotlin Extension:
fun String.isValidEmail() =
!TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()
Don't use a reg-ex.
Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "user#gmail.com.nospam", as will org.apache.commons.validator.routines.EmailValidator)
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.
If you want to perform some basic checks you could just check that it's in the form *#*
If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.
Use simple one line code for email Validation
public static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
use like...
if (!isValidEmail(yourEdittext.getText().toString()) {
Toast.makeText(context, "your email is not valid", 2000).show();
}
You could write a Kotlin extension like this:
fun String.isValidEmail() =
isNotEmpty() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
And then call it like this:
email.isValidEmail()
This is Android Studio suggestions:
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
use android:inputType="textEmailAddress" as below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:inputType="textEmailAddress"
android:id="#+id/email"
/>
and:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
.matches();
}
You can use regular expression to do so. Something like the following.
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
String email = "xyz#xyzdomain.com";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();
Note: Check the regular expression given above, don't use it as it is.
There is a Patterns class in package android.util which is beneficial here. Below is the method I always use for validating email and many other stuffs
private boolean isEmailValid(String email) {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
this is the best way in kotlin Useing Extension Function
fun String.isEmailValid(): Boolean {
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
Simplest Kotlin solution using extension functions:
fun String.isEmailValid() =
Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
).matcher(this).matches()
and then you can validate like this:
"testemail6589#gmail.com".isEmailValid()
If you are in kotlin-multiplatform without access to Pattern, this is the equivalent:
fun String.isValidEmail() = Regex(emailRegexStr).matches(this)
Call This Method where you want to validate email ID.
public static boolean isValid(String email)
{
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
For an Email validation android provide some InBuilt Pattern.But it only support API level 8 and above.
Here is code for use that pattern to check email validation.
private boolean Email_Validate(String email)
{
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Make sure that after execute this method you should check that if this method return true then you allow to save email and if this method return false then display message that email is "Invalid".
Hope you get your answer,
Thanks you.
Can I STRONGLY recommend you don't try to 'validate' email addresses, you'll just get yourself into a lot of work for no good reason.
Just make sure what is entered won't break your own code - e.g. no spaces or illegal characters which might cause an Exception.
Anything else will just cause you a lot of work for minimal return...
public boolean isValidEmail(String email)
{
boolean isValidEmail = false;
String emailExpression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
isValidEmail = true;
}
return isValidEmail;
}
If you are using API 8 or above, you can use the readily available Patterns class to validate email. Sample code:
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java file into your project and reference it. You can get the source code for Patterns.java from this link
Here is android.util.Patterns.EMAIL_ADDRESS
[a-zA-Z0-9+._\%-+]{1,256}\#[a-zA-Z0-9][a-zA-Z0-9-]{0,64}(.[a-zA-Z0-9][a-zA-Z0-9-]{0,25})+
String will match it if
Start by 1->256 character in (a-z, A-Z, 0-9, +, ., _, %, - , +)
then 1 '#' character
then 1 character in (a-z, A-Z, 0-9)
then 0->64 character in (a-z, A-Z, 0-9, -)
then **ONE OR MORE**
1 '.' character
then 1 character in (a-z, A-Z, 0-9)
then 0->25 character in (a-z, A-Z, 0-9, -)
Example some special match email
a#b.c
a+#b-.c
a#b.c.d.e.f.g.h
You may modify this pattern for your case then validate by
fun isValidEmail(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Try this simple method which can not accept the email address beginning with digits:
boolean checkEmailCorrect(String Email) {
if(signupEmail.length() == 0) {
return false;
}
String pttn = "^\\D.+#.+\\.[a-z]+";
Pattern p = Pattern.compile(pttn);
Matcher m = p.matcher(Email);
if(m.matches()) {
return true;
}
return false;
}
Try this code.. Its really works..
if (!email
.matches("^[\\w-_\\.+]*[\\w-_\\.]\\#([\\w]+\\.)+[\\w]+[\\w]$"))
{
Toast.makeText(getApplicationContext(), "Email is invalid",
Toast.LENGTH_LONG).show();
return;
}
Following was used by me. However it contains extra characters than normal emails but this was a requirement for me.
public boolean isValidEmail(String inputString) {
String s ="^((?!.*?\.\.)[A-Za-z0-9\.\!\#\$\%\&\'*\+\-\/\=\?\^_`\{\|\}\~]+#[A-Za-z0-9]+[A-Za-z0-9\-\.]+\.[A-Za-z0-9\-\.]+[A-Za-z0-9]+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
return matcher.matches();
}
Answer of this question:-
Requirement to validate an e-mail address with given points
Explanation-
(?!.*?..) "Negative Lookhead" to negate 2 consecutive dots.
[A-Za-z0-9.!#\$\%\&\'*+-/\=\?\^_`{\|}\~]+ Atleast one
characters defined. ("\" is used for escaping).
# There might be one "#".
[A-Za-z0-9]+ then atleast one character defined.
[A-Za-z0-9-.]* Zero or any repetition of character defined.
[A-Za-z0-9]+ Atleast one char after dot.
The key here is that you want to fully validate the email address. You don’t just want to check it for syntactic correctness, you want to check whether the email address is real.
Two obvious reasons: real users often mis-type their email addresses, and some users may put in fake email addresses. Therefore, you want to do a syntactic check and an existence check.
The best way to do this that I have found on Android is to use the free Cloudmersive Validation API for this.
The code looks like this:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
EmailApi apiInstance = new EmailApi();
String email = "email_example"; // String | Email address to validate, e.g. \"support#cloudmersive.com\". The input is a string so be sure to enclose it in double-quotes.
try {
FullEmailValidationResponse result = apiInstance.emailFullValidation(email);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EmailApi#emailFullValidation");
e.printStackTrace();
}
I’m using this in all my apps and it is great because I can validate the email addresses in the UX at the point of entry.
According to Patterns.EMAIL_ADDRESS, this email is correct "abc#abc.c". So I modified the regex in Patterns.EMAIL_ADDRESS and increased the minimum length for domain.
Here is the function for Kotlin:
fun isEmailValid(email: String): Boolean =
email.isNotEmpty() && Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{1,25}" +
")+"
).matcher(email).matches()
I just changed domain part from {0,25} to {1,25}.
Email Validation in Kotlin:
val email = etEmail.text.toString().trim() // get email from user
if(isValidEmail(email)){ // call isValidEmail function and pass email in parameter
// Your email ID is Valid
}else{
// Enter your valid email ID
}
This method is used for checking valid email id formats.
fun isValidEmail(email: CharSequence): Boolean {
var isValid = true
val expression = "^[\\w.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$"
val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(email)
if (!matcher.matches()) {
isValid = false
}
return isValid
}
Note that most of the regular expressions are not valid for international domain names (IDN) and new top level domains like .mobi or .info (if you check for country codes or .org, .com, .gov and so on).
A valid check should separate the local part (before the at-sign) and the domain part. You should also consider the max length of the local part and domain (in sum 255 chars including the at-sign).
The best approach is to transform the address in an IDN compatible format (if required), validate the local part (RFC), check the length of the address and the check the availability of the domain (DNS MX lookup) or simply send an email.
The Linkify class has some pretty useful helper methods that might be relevant, including regular expressions designed to pick up phone numbers and email addresses and such:
http://developer.android.com/reference/android/text/util/Linkify.html
I have used follwing code.This works grate.I hope this will help you.
if (validMail(yourEmailString)){
//do your stuf
}else{
//email is not valid.
}
and use follwing method.This returns true if email is valid.
private boolean validMail(String yourEmailString) {
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(emailstring);
return emailMatcher.matches();
}
email is your email-is.
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
For regex lovers, the very best (e.g. consistant with RFC 822) email's pattern I ever found since now is the following (before PHP supplied filters). I guess it's easy to translate this into Java - for those playing with API < 8 :
private static function email_regex_pattern() {
// Source: http://www.iamcal.com/publish/articles/php/parsing_email
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$pattern = "!^$local_part\\x40$domain$!";
return $pattern ;
}

email validation android [duplicate]

What's a good technique for validating an e-mail address (e.g. from a user input field) in Android? org.apache.commons.validator.routines.EmailValidator doesn't seem to be available. Are there any other libraries doing this which are included in Android already or would I have to use RegExp?
Another option is the built in Patterns starting with API Level 8:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Patterns viewable source
OR
One line solution from #AdamvandenHoven:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
Next pattern is used in K-9 mail:
public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
You can use function
private boolean checkEmail(String email) {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
Since API 8 (android 2.2) there is a pattern: android.util.Patterns.EMAIL_ADDRESS
http://developer.android.com/reference/android/util/Patterns.html
So you can use it to validate yourEmailString:
private boolean isValidEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
returns true if the email is valid
UPD:
This pattern source code is:
public static final Pattern EMAIL_ADDRESS
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
refer to: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/util/Patterns.java
So you can build it yourself for compatibility with API < 8.
We have a simple Email pattern matcher now.
Java:
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Kotlin Function:
private fun isValidEmail(email: String): Boolean {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Kotlin Extension:
fun String.isValidEmail() =
!TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()
Don't use a reg-ex.
Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "user#gmail.com.nospam", as will org.apache.commons.validator.routines.EmailValidator)
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.
If you want to perform some basic checks you could just check that it's in the form *#*
If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.
Use simple one line code for email Validation
public static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
use like...
if (!isValidEmail(yourEdittext.getText().toString()) {
Toast.makeText(context, "your email is not valid", 2000).show();
}
You could write a Kotlin extension like this:
fun String.isValidEmail() =
isNotEmpty() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
And then call it like this:
email.isValidEmail()
This is Android Studio suggestions:
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
use android:inputType="textEmailAddress" as below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:inputType="textEmailAddress"
android:id="#+id/email"
/>
and:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
.matches();
}
You can use regular expression to do so. Something like the following.
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
String email = "xyz#xyzdomain.com";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();
Note: Check the regular expression given above, don't use it as it is.
There is a Patterns class in package android.util which is beneficial here. Below is the method I always use for validating email and many other stuffs
private boolean isEmailValid(String email) {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
this is the best way in kotlin Useing Extension Function
fun String.isEmailValid(): Boolean {
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
Simplest Kotlin solution using extension functions:
fun String.isEmailValid() =
Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
).matcher(this).matches()
and then you can validate like this:
"testemail6589#gmail.com".isEmailValid()
If you are in kotlin-multiplatform without access to Pattern, this is the equivalent:
fun String.isValidEmail() = Regex(emailRegexStr).matches(this)
Call This Method where you want to validate email ID.
public static boolean isValid(String email)
{
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
For an Email validation android provide some InBuilt Pattern.But it only support API level 8 and above.
Here is code for use that pattern to check email validation.
private boolean Email_Validate(String email)
{
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Make sure that after execute this method you should check that if this method return true then you allow to save email and if this method return false then display message that email is "Invalid".
Hope you get your answer,
Thanks you.
Can I STRONGLY recommend you don't try to 'validate' email addresses, you'll just get yourself into a lot of work for no good reason.
Just make sure what is entered won't break your own code - e.g. no spaces or illegal characters which might cause an Exception.
Anything else will just cause you a lot of work for minimal return...
public boolean isValidEmail(String email)
{
boolean isValidEmail = false;
String emailExpression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
isValidEmail = true;
}
return isValidEmail;
}
If you are using API 8 or above, you can use the readily available Patterns class to validate email. Sample code:
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java file into your project and reference it. You can get the source code for Patterns.java from this link
Here is android.util.Patterns.EMAIL_ADDRESS
[a-zA-Z0-9+._\%-+]{1,256}\#[a-zA-Z0-9][a-zA-Z0-9-]{0,64}(.[a-zA-Z0-9][a-zA-Z0-9-]{0,25})+
String will match it if
Start by 1->256 character in (a-z, A-Z, 0-9, +, ., _, %, - , +)
then 1 '#' character
then 1 character in (a-z, A-Z, 0-9)
then 0->64 character in (a-z, A-Z, 0-9, -)
then **ONE OR MORE**
1 '.' character
then 1 character in (a-z, A-Z, 0-9)
then 0->25 character in (a-z, A-Z, 0-9, -)
Example some special match email
a#b.c
a+#b-.c
a#b.c.d.e.f.g.h
You may modify this pattern for your case then validate by
fun isValidEmail(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Try this simple method which can not accept the email address beginning with digits:
boolean checkEmailCorrect(String Email) {
if(signupEmail.length() == 0) {
return false;
}
String pttn = "^\\D.+#.+\\.[a-z]+";
Pattern p = Pattern.compile(pttn);
Matcher m = p.matcher(Email);
if(m.matches()) {
return true;
}
return false;
}
Try this code.. Its really works..
if (!email
.matches("^[\\w-_\\.+]*[\\w-_\\.]\\#([\\w]+\\.)+[\\w]+[\\w]$"))
{
Toast.makeText(getApplicationContext(), "Email is invalid",
Toast.LENGTH_LONG).show();
return;
}
Following was used by me. However it contains extra characters than normal emails but this was a requirement for me.
public boolean isValidEmail(String inputString) {
String s ="^((?!.*?\.\.)[A-Za-z0-9\.\!\#\$\%\&\'*\+\-\/\=\?\^_`\{\|\}\~]+#[A-Za-z0-9]+[A-Za-z0-9\-\.]+\.[A-Za-z0-9\-\.]+[A-Za-z0-9]+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
return matcher.matches();
}
Answer of this question:-
Requirement to validate an e-mail address with given points
Explanation-
(?!.*?..) "Negative Lookhead" to negate 2 consecutive dots.
[A-Za-z0-9.!#\$\%\&\'*+-/\=\?\^_`{\|}\~]+ Atleast one
characters defined. ("\" is used for escaping).
# There might be one "#".
[A-Za-z0-9]+ then atleast one character defined.
[A-Za-z0-9-.]* Zero or any repetition of character defined.
[A-Za-z0-9]+ Atleast one char after dot.
The key here is that you want to fully validate the email address. You don’t just want to check it for syntactic correctness, you want to check whether the email address is real.
Two obvious reasons: real users often mis-type their email addresses, and some users may put in fake email addresses. Therefore, you want to do a syntactic check and an existence check.
The best way to do this that I have found on Android is to use the free Cloudmersive Validation API for this.
The code looks like this:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
EmailApi apiInstance = new EmailApi();
String email = "email_example"; // String | Email address to validate, e.g. \"support#cloudmersive.com\". The input is a string so be sure to enclose it in double-quotes.
try {
FullEmailValidationResponse result = apiInstance.emailFullValidation(email);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EmailApi#emailFullValidation");
e.printStackTrace();
}
I’m using this in all my apps and it is great because I can validate the email addresses in the UX at the point of entry.
According to Patterns.EMAIL_ADDRESS, this email is correct "abc#abc.c". So I modified the regex in Patterns.EMAIL_ADDRESS and increased the minimum length for domain.
Here is the function for Kotlin:
fun isEmailValid(email: String): Boolean =
email.isNotEmpty() && Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{1,25}" +
")+"
).matcher(email).matches()
I just changed domain part from {0,25} to {1,25}.
Email Validation in Kotlin:
val email = etEmail.text.toString().trim() // get email from user
if(isValidEmail(email)){ // call isValidEmail function and pass email in parameter
// Your email ID is Valid
}else{
// Enter your valid email ID
}
This method is used for checking valid email id formats.
fun isValidEmail(email: CharSequence): Boolean {
var isValid = true
val expression = "^[\\w.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$"
val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(email)
if (!matcher.matches()) {
isValid = false
}
return isValid
}
Note that most of the regular expressions are not valid for international domain names (IDN) and new top level domains like .mobi or .info (if you check for country codes or .org, .com, .gov and so on).
A valid check should separate the local part (before the at-sign) and the domain part. You should also consider the max length of the local part and domain (in sum 255 chars including the at-sign).
The best approach is to transform the address in an IDN compatible format (if required), validate the local part (RFC), check the length of the address and the check the availability of the domain (DNS MX lookup) or simply send an email.
The Linkify class has some pretty useful helper methods that might be relevant, including regular expressions designed to pick up phone numbers and email addresses and such:
http://developer.android.com/reference/android/text/util/Linkify.html
I have used follwing code.This works grate.I hope this will help you.
if (validMail(yourEmailString)){
//do your stuf
}else{
//email is not valid.
}
and use follwing method.This returns true if email is valid.
private boolean validMail(String yourEmailString) {
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(emailstring);
return emailMatcher.matches();
}
email is your email-is.
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
For regex lovers, the very best (e.g. consistant with RFC 822) email's pattern I ever found since now is the following (before PHP supplied filters). I guess it's easy to translate this into Java - for those playing with API < 8 :
private static function email_regex_pattern() {
// Source: http://www.iamcal.com/publish/articles/php/parsing_email
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$pattern = "!^$local_part\\x40$domain$!";
return $pattern ;
}

How should I validate an e-mail address?

What's a good technique for validating an e-mail address (e.g. from a user input field) in Android? org.apache.commons.validator.routines.EmailValidator doesn't seem to be available. Are there any other libraries doing this which are included in Android already or would I have to use RegExp?
Another option is the built in Patterns starting with API Level 8:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Patterns viewable source
OR
One line solution from #AdamvandenHoven:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
Next pattern is used in K-9 mail:
public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
You can use function
private boolean checkEmail(String email) {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
Since API 8 (android 2.2) there is a pattern: android.util.Patterns.EMAIL_ADDRESS
http://developer.android.com/reference/android/util/Patterns.html
So you can use it to validate yourEmailString:
private boolean isValidEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
returns true if the email is valid
UPD:
This pattern source code is:
public static final Pattern EMAIL_ADDRESS
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
refer to: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/util/Patterns.java
So you can build it yourself for compatibility with API < 8.
We have a simple Email pattern matcher now.
Java:
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Kotlin Function:
private fun isValidEmail(email: String): Boolean {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Kotlin Extension:
fun String.isValidEmail() =
!TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()
Don't use a reg-ex.
Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "user#gmail.com.nospam", as will org.apache.commons.validator.routines.EmailValidator)
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.
If you want to perform some basic checks you could just check that it's in the form *#*
If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.
Use simple one line code for email Validation
public static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
use like...
if (!isValidEmail(yourEdittext.getText().toString()) {
Toast.makeText(context, "your email is not valid", 2000).show();
}
You could write a Kotlin extension like this:
fun String.isValidEmail() =
isNotEmpty() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
And then call it like this:
email.isValidEmail()
This is Android Studio suggestions:
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
use android:inputType="textEmailAddress" as below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:inputType="textEmailAddress"
android:id="#+id/email"
/>
and:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
.matches();
}
You can use regular expression to do so. Something like the following.
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
String email = "xyz#xyzdomain.com";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();
Note: Check the regular expression given above, don't use it as it is.
There is a Patterns class in package android.util which is beneficial here. Below is the method I always use for validating email and many other stuffs
private boolean isEmailValid(String email) {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
this is the best way in kotlin Useing Extension Function
fun String.isEmailValid(): Boolean {
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
Simplest Kotlin solution using extension functions:
fun String.isEmailValid() =
Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
).matcher(this).matches()
and then you can validate like this:
"testemail6589#gmail.com".isEmailValid()
If you are in kotlin-multiplatform without access to Pattern, this is the equivalent:
fun String.isValidEmail() = Regex(emailRegexStr).matches(this)
Call This Method where you want to validate email ID.
public static boolean isValid(String email)
{
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
For an Email validation android provide some InBuilt Pattern.But it only support API level 8 and above.
Here is code for use that pattern to check email validation.
private boolean Email_Validate(String email)
{
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Make sure that after execute this method you should check that if this method return true then you allow to save email and if this method return false then display message that email is "Invalid".
Hope you get your answer,
Thanks you.
Can I STRONGLY recommend you don't try to 'validate' email addresses, you'll just get yourself into a lot of work for no good reason.
Just make sure what is entered won't break your own code - e.g. no spaces or illegal characters which might cause an Exception.
Anything else will just cause you a lot of work for minimal return...
public boolean isValidEmail(String email)
{
boolean isValidEmail = false;
String emailExpression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
isValidEmail = true;
}
return isValidEmail;
}
If you are using API 8 or above, you can use the readily available Patterns class to validate email. Sample code:
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java file into your project and reference it. You can get the source code for Patterns.java from this link
Here is android.util.Patterns.EMAIL_ADDRESS
[a-zA-Z0-9+._\%-+]{1,256}\#[a-zA-Z0-9][a-zA-Z0-9-]{0,64}(.[a-zA-Z0-9][a-zA-Z0-9-]{0,25})+
String will match it if
Start by 1->256 character in (a-z, A-Z, 0-9, +, ., _, %, - , +)
then 1 '#' character
then 1 character in (a-z, A-Z, 0-9)
then 0->64 character in (a-z, A-Z, 0-9, -)
then **ONE OR MORE**
1 '.' character
then 1 character in (a-z, A-Z, 0-9)
then 0->25 character in (a-z, A-Z, 0-9, -)
Example some special match email
a#b.c
a+#b-.c
a#b.c.d.e.f.g.h
You may modify this pattern for your case then validate by
fun isValidEmail(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Try this simple method which can not accept the email address beginning with digits:
boolean checkEmailCorrect(String Email) {
if(signupEmail.length() == 0) {
return false;
}
String pttn = "^\\D.+#.+\\.[a-z]+";
Pattern p = Pattern.compile(pttn);
Matcher m = p.matcher(Email);
if(m.matches()) {
return true;
}
return false;
}
Try this code.. Its really works..
if (!email
.matches("^[\\w-_\\.+]*[\\w-_\\.]\\#([\\w]+\\.)+[\\w]+[\\w]$"))
{
Toast.makeText(getApplicationContext(), "Email is invalid",
Toast.LENGTH_LONG).show();
return;
}
Following was used by me. However it contains extra characters than normal emails but this was a requirement for me.
public boolean isValidEmail(String inputString) {
String s ="^((?!.*?\.\.)[A-Za-z0-9\.\!\#\$\%\&\'*\+\-\/\=\?\^_`\{\|\}\~]+#[A-Za-z0-9]+[A-Za-z0-9\-\.]+\.[A-Za-z0-9\-\.]+[A-Za-z0-9]+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
return matcher.matches();
}
Answer of this question:-
Requirement to validate an e-mail address with given points
Explanation-
(?!.*?..) "Negative Lookhead" to negate 2 consecutive dots.
[A-Za-z0-9.!#\$\%\&\'*+-/\=\?\^_`{\|}\~]+ Atleast one
characters defined. ("\" is used for escaping).
# There might be one "#".
[A-Za-z0-9]+ then atleast one character defined.
[A-Za-z0-9-.]* Zero or any repetition of character defined.
[A-Za-z0-9]+ Atleast one char after dot.
The key here is that you want to fully validate the email address. You don’t just want to check it for syntactic correctness, you want to check whether the email address is real.
Two obvious reasons: real users often mis-type their email addresses, and some users may put in fake email addresses. Therefore, you want to do a syntactic check and an existence check.
The best way to do this that I have found on Android is to use the free Cloudmersive Validation API for this.
The code looks like this:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
EmailApi apiInstance = new EmailApi();
String email = "email_example"; // String | Email address to validate, e.g. \"support#cloudmersive.com\". The input is a string so be sure to enclose it in double-quotes.
try {
FullEmailValidationResponse result = apiInstance.emailFullValidation(email);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EmailApi#emailFullValidation");
e.printStackTrace();
}
I’m using this in all my apps and it is great because I can validate the email addresses in the UX at the point of entry.
According to Patterns.EMAIL_ADDRESS, this email is correct "abc#abc.c". So I modified the regex in Patterns.EMAIL_ADDRESS and increased the minimum length for domain.
Here is the function for Kotlin:
fun isEmailValid(email: String): Boolean =
email.isNotEmpty() && Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{1,25}" +
")+"
).matcher(email).matches()
I just changed domain part from {0,25} to {1,25}.
Email Validation in Kotlin:
val email = etEmail.text.toString().trim() // get email from user
if(isValidEmail(email)){ // call isValidEmail function and pass email in parameter
// Your email ID is Valid
}else{
// Enter your valid email ID
}
This method is used for checking valid email id formats.
fun isValidEmail(email: CharSequence): Boolean {
var isValid = true
val expression = "^[\\w.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$"
val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(email)
if (!matcher.matches()) {
isValid = false
}
return isValid
}
Note that most of the regular expressions are not valid for international domain names (IDN) and new top level domains like .mobi or .info (if you check for country codes or .org, .com, .gov and so on).
A valid check should separate the local part (before the at-sign) and the domain part. You should also consider the max length of the local part and domain (in sum 255 chars including the at-sign).
The best approach is to transform the address in an IDN compatible format (if required), validate the local part (RFC), check the length of the address and the check the availability of the domain (DNS MX lookup) or simply send an email.
The Linkify class has some pretty useful helper methods that might be relevant, including regular expressions designed to pick up phone numbers and email addresses and such:
http://developer.android.com/reference/android/text/util/Linkify.html
I have used follwing code.This works grate.I hope this will help you.
if (validMail(yourEmailString)){
//do your stuf
}else{
//email is not valid.
}
and use follwing method.This returns true if email is valid.
private boolean validMail(String yourEmailString) {
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(emailstring);
return emailMatcher.matches();
}
email is your email-is.
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
For regex lovers, the very best (e.g. consistant with RFC 822) email's pattern I ever found since now is the following (before PHP supplied filters). I guess it's easy to translate this into Java - for those playing with API < 8 :
private static function email_regex_pattern() {
// Source: http://www.iamcal.com/publish/articles/php/parsing_email
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$pattern = "!^$local_part\\x40$domain$!";
return $pattern ;
}

Categories

Resources