Email validation on EditText - Android - android

I have an Email EditText and i want to check it using email validation.
This's my email validation code
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public void showAlertValidation() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RegisterActivity.this);
alertDialog.setTitle("Failed");
alertDialog.setMessage("Invalid Email");
alertDialog.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
And this is my EditText validation code
editTextEmail= (EditText) findViewById(R.id.editTextEmail);
email = editTextEmail.getText().toString();
if(email.length() == 0) {
editTextEmail.setError("Email required!");
if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else{
showAlertValidation();
}
}
The problem is the result of the EditText. When the value of EditText is null, it run showAlertValidation();
But if the value of EditText is "email" or "email#example" or "email#example.com", it not run showAlertValidation();
Anything wrong with my code?

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()

You are mistakenly comparing your EditText text length to 0, and only if it's true, you do your validation logic.
Here is is the correct code:
#Override
public void onClick(View v) {
String email = editTextEmail.getText().toString();
if(email.length() != 0) {
if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(), "Valid email address!", Toast.LENGTH_SHORT).show();
}
else{
editTextEmail.setError("Email required!");
showAlertValidation();
}
}
else{
editTextEmail.setError("Email required!");
}
}

Its better to make a class which validates the email. So that you can reuse it anywhere you need. You don't even need to put the text of edittext in separate string. Make the following class:
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static EmailValidator sInstance;
public static EmailValidator getInstance() {
if (sInstance == null) {
sInstance = new EmailValidator();
}
return sInstance;
}
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}}
Now use this class to check for validation of email of edittext like this:
if(!EmailValidator.getInstance().validate(editTextEmail.getText().toString().trim())){
editTextEmail.setError("Invalid email address");
}
Hope this helps.

you should clear space " " before check length of email string with String.trim();
if(email.trim().length() == 0) {//code here}

Problem is your if condition
if(email.length() == 0)
{
editTextEmail.setError("Email required!");
if (isValidEmail(email))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
showAlertValidation();
}
}
As it only validates your email address when your editText is empty.
What you can do is :
email.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)
{
if(s.length() > 0)
{
if (isValidEmail(email))
{
editTextEmail.setError(null);
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"valid email address Required",Toast.LENGTH_SHORT).show();
}
}
}
});

I think this is where you made a mistake (EditText validation code):
editTextEmail= (EditText) findViewById(R.id.editTextEmail);
email = editTextEmail.getText().toString();
if(email.length() == 0) {
editTextEmail.setError("Email required!");
}
else if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else{
showAlertValidation();
}

Related

Multiuser in Android Studio using Realtime Firebase

When I run the codes, it does not show any error. I have no problem to login as guardian but when I try to login as elderly it couldn't and I don't know what's the problem. What I want is when a user input the username and password, it will validate from database and direct the user according to different user type.
Segment codes of Login.java:
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Field cannot be empty");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Field cannot be empty");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate login info
if (!validateUsername() || !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String input1 = username.getEditText().getText().toString();
String input2 = password.getEditText().getText().toString();
if (dataSnapshot.child(input1).exists()) {
if (dataSnapshot.child(input1).child("password").getValue(String.class).equals(input2)) {
if (active.isChecked()) {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Guardian");
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Elderly");
startActivity(new Intent(Login.this, dashboardUser.class));
}
} else {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardUser.class));
}
}
} else {
password.setError("Wrong Password");
password.requestFocus();
}
} else {
username.setError("No such User exist");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onStart() {
super.onStart();
if (preferences.getDataLogin(this)) {
if (preferences.getDataAs(this).equals("Guardian")) {
startActivity(new Intent(this, dashboardGuardian.class));
finish();
} else {
startActivity(new Intent(this, dashboardUser.class));
finish();
}
}
}
}
Codes of Register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout regUsername, regEmail, regPhoneNo, regPassword;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
UserHelperClass helperClass;
int i = 0;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Hooks to all xml elements in activity_register.xml
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNo);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
helperClass = new UserHelperClass();
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("user");
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
String username = regUsername.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(username).setValue(helperClass);
}
});
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White space is not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
return true;
}
}
private Boolean validateUserType() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please select user type", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white space
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
public void registerUser(View view) {
if (!validateUsername() | !validatePassword() | !validatePhoneNo() | !validateEmail() | validateUserType()) {
return;
}
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(String.valueOf(i + 1)).setValue(helperClass);
}
}
Database structure
If you post your database structure that would be more helpful.
As per your code.
you have two children in input1
'radioGuardian' and 'radioElderly'
have you added both values on registration? Or it will be null. And it will produce nullPointEx.
Hence the issue is here!
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
Try to change it to:-
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
helperClass.setRadioGuardian("NA");
} else {
helperClass.setRadioGuardian(m2);
helperClass.setRadioElderly("NA");
}

Email id and phone number not validating

Hi In My application checking validation for email id and phone number but it's not validating both and simply it's saving into database.
I want to check the email id and phone number if it's both correct i want to do next process
Can any one please help me
ContactUs.java
public class ContactUs extends Activity
{
EditText fname1,lname1,mobile1,altmob1,email1,comment1;
String data="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1=(EditText) findViewById(R.id.fname);
lname1=(EditText) findViewById(R.id.lname);
mobile1=(EditText) findViewById(R.id.mobile);
altmob1=(EditText) findViewById(R.id.altno);
email1=(EditText) findViewById(R.id.email);
comment1=(EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String fname = fname1.getText().toString();
String lname = lname1.getText().toString();
String mobile = mobile1.getText().toString();
String altmob = altmob1.getText().toString();
String email = email1.getText().toString();
String comment = comment1.getText().toString();
if(fname.equals(""))
{
fname1.setError( "Please Enter First Name" );
}
else if(lname.equals(""))
{
lname1.setError( "Please Enter Last Name" );
}
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
else if(altmob.equals(""))
{
altmob1.setError( "Please Enter Altenative Mobile No." );
}
else if(email.equals(""))
{
email1.setError( "Please Enter EmailId" );
isValidMail(email);
}
else if(comment.equals(""))
{
comment1.setError( "Please Enter Your Comments here" );
}
else
{
try{
String queryString ="fname="+ fname
+"&lname="+lname+"&mobile="+mobile+ "&altmob="+altmob+"&email="+email+"&comment="+comment;
data = DatabaseUtility.executeQueryPhp("Contactform",queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private boolean isValidMail(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();
if(!check)
{
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile)
{
boolean check;
if(mobile.length() < 6 || mobile.length() > 13)
{
check = false;
mobile1.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
there are edittext box with property email
android:inputType="textEmailAddress"
in your code
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
it check if email in blank then go to isValidMobile
so use
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile)){
// do somting
}
and similar for email
You are running your valid email check but ignoring the result. As long as you enter some text the call to save will work.
If you incorporate the return values from your is valid check methods, you can stop saving when those calls return false.
e.g.
if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile))
{
mobile1.setError("Not Valid Number");
}
Try this for checking email:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
For telephone number check:
public final static boolean isValidPhone(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
And please update your code with as :
public class ContactUs extends Activity {
EditText fname1, lname1, mobile1, altmob1, email1, comment1;
String data = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1 = (EditText) findViewById(R.id.fname);
lname1 = (EditText) findViewById(R.id.lname);
mobile1 = (EditText) findViewById(R.id.mobile);
altmob1 = (EditText) findViewById(R.id.altno);
email1 = (EditText) findViewById(R.id.email);
comment1 = (EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fname = fname1.getText().toString().trim();
String lname = lname1.getText().toString().trim();
String mobile = mobile1.getText().toString().trim();
String altmob = altmob1.getText().toString().trim();
String email = email1.getText().toString().trim();
String comment = comment1.getText().toString().trim();
if (fname.length() != 0) {
if (lname.length() != 0) {
if (mobile.length() != 0 && isValidMobile(mobile)) {
if (altmob.length() != 0 && isValidMobile(altmob)) {
if (email.length() != 0 && isValidMail(email)) {
if (comment.length() != 0) {
try {
String queryString = "fname="
+ fname + "&lname=" + lname
+ "&mobile=" + mobile
+ "&altmob=" + altmob
+ "&email=" + email
+ "&comment=" + comment;
data = DatabaseUtility
.executeQueryPhp(
"Contactform",
queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
comment1.setError("Please Enter Your Comments here");
}
} else {
email1.setError("Please Enter Valid EmailId");
}
} else {
altmob1.setError("Please Enter Altenative Mobile No.");
}
} else {
mobile1.setError("Please Enter valid Mobile No.");
}
} else {
lname1.setError("Please Enter Last Name");
}
} else {
fname1.setError("Please Enter First Name");
}
}
});
}
private boolean isValidMail(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();
if (!check) {
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile) {
boolean check;
if (mobile.length() < 6 || mobile.length() > 13) {
check = false;
mobile1.setError("Not Valid Number");
} else {
check = true;
}
return check;
}
}

Android Email Validation on EditText

I have one edittext and I would to to write email validation in my Editttext
this is a xml code
<EditText
android:id="#+id/mail"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignLeft="#+id/phone"
android:layout_below="#+id/phone"
android:layout_marginRight="33dp"
android:layout_marginTop="10dp"
android:background="#drawable/edit_background"
android:ems="10"
android:hint="E-Mail"
android:inputType="textEmailAddress"
android:paddingLeft="20dp"
android:textColor="#7e7e7e"
android:textColorHint="#7e7e7e" >
</EditText>
and this is a java code
emailInput = mail.getText().toString().trim();
emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if (emailInput.matches(emailPattern)) {
Toast.makeText(getActivity(), "valid email address", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Invalid email address", Toast.LENGTH_SHORT).show();
mail.setBackgroundResource(R.drawable.edit_red_line);
}
I can't validation. The toast message is always "Invalid email address".
What am I doing wrong?
Why not use:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
As suggested here.
I am posting very simple and easy answer of email validation without using any string pattern.
1.Set on click listener on button....
button_resetPassword.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CharSequence temp_emilID=username.getText().toString();//here username is the your edittext object...
if(!isValidEmail(temp_emilID))
{
username.requestFocus();
username.setError("Enter Correct Mail_ID ..!!");
or
Toast.makeText(getApplicationContext(), "Enter Correct Mail_ID", Toast.LENGTH_SHORT).show();
}
else
{
correctMail..
//Your action...
}
});
2.call the isValidEmail() i.e..
public final static boolean isValidEmail(CharSequence target)
{
if (TextUtils.isEmpty(target))
{
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
I hope it will helpful for you...
Android Email Validation Simplest way
String validemail= "[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 emal=email.getText().toString();
Matcher matcherObj = Pattern.compile(validemail).matcher(emal);
if (matcherObj.matches()) {
Toast.makeText(getApplicationContext(), "enter
all details", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"please enter
valid email",Toast.LENGTH_SHORT).show();
}
Try following code:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
This works fine.
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(emailId.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"enter email address",Toast.LENGTH_SHORT).show();
else {
if (emailId.getText().toString().trim().matches(emailPattern)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
}
here is a whole code for login validations......
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
#Bind(R.id.input_email) EditText _emailText;
#Bind(R.id.input_password) EditText _passwordText;
#Bind(R.id.btn_login) Button _loginButton;
#Bind(R.id.link_signup) TextView _signupLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
Use this function for validating email id:
private boolean validateEmaillId(String emailId){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(emailId).matches();
}
I had a query in email pattern for more than one Email ID validation and for only one Email ID.I solved it by using :
public static final String patter_emails="^(\\s*,?\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*#([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]{2,9})+\\s*$";
public static final String patter_email="^(\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*#([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]{2,9})+\\s*$";
These above is used for pattern in Java and Android both.
check this by using:
pattern test: rubular.com
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()
private void isValidEmail(String email_id) {
if (email_id == null){
checkTextView.setVisibility(View.VISIBLE);
checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
return;
}
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email_id).matches()) {
checkTextView.setVisibility(View.GONE);
} else {
checkTextView.setVisibility(View.VISIBLE);
checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
}
Take a textView ex.checkTextView and validate when the email is valid then the textview is gone otherwise it show the message
Try this code
String emailPattern = "(?:[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])+)\\])";
if (!tvEmail.matches(Constants.emailPattern)){
tvEmail.setError("Invalid Email ");
}
else{
//your code
}
String emailPattern = "(?:[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])+)\\])";
if (!"anan.pp#gmail.co".matches(Constants.emailPattern)){
//tvEmail.setError("Invalid Email ");
} else {
// your code
}
Try below code:
Just call below method like,
if(emailValidator(mail.getText().toString())){
Toast.makeText(getActivity(), "valid email address",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "invalid email address",
Toast.LENGTH_SHORT).show();
}
public static boolean emailValidator(final String mailAddress) {
Pattern pattern;
Matcher matcher;
final 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(mailAddress);
return matcher.matches();
}
Assign a String variable to store the value of this EditText:
emailInput = mail.getText().toString().trim();
Use setError in your EditText:
if(!isValidEmail(emailInput)){
mail.setError("Invalid"); /*"Invalid Text" or something like getString(R.string.Invalid)*/
mail.requestFocus();
}
Create a method to check the email:
private boolean isValidEmail(String emailInput) {
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 = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(emailInput);
return matcher.matches();
}

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.
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();
}
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;
}
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();
}
}
}
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.
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()
}
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();
}
The built in PHONE pattern matcher does not work in all cases.
So far, this is the best solution I have found to validate a phone number (code in Kotlin, extension of String)
fun String.isValidPhoneNumber() : Boolean {
val patterns = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"
return Pattern.compile(patterns).matcher(this).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.
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;
}
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;
}
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 test#gmail.com
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
}
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();
}
private fun isValidMobileNumber(s: String): Boolean {
// 1) Begins with 0 or 91
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
val p: Pattern = Pattern.compile("(0|91)?[6-9][0-9]{9}")
// Pattern class contains matcher() method
// to find matching between given number
val m: Matcher = p.matcher(s)
return m.find() && m.group().equals(s)
}

Email Validation on EditText in android

I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").
I don't want that it login with "\".`
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.main);
WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);
this.pref = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
register = (Button) findViewById(R.id.btnregister);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RegisterIntent();
}
});
login = (Button) findViewById(R.id.btlogin);
password = (EditText) findViewById(R.id.txtPwd);
username = (EditText) findViewById(R.id.txtemail);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
pref = getSharedPreferences(Constants.PREFS_NAME,
MODE_PRIVATE);
String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
"");
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLogin = pref.getBoolean("saveLogin", false);
if (saveLogin == true) {
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLoginCheckBox.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Constants.clearInfo();
getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(Constants.PREF_USERNAME,
username.getText().toString())
.putString(Constants.PREF_PASSWORD,
password.getText().toString())
.putString(Constants.PREF_CHECKED, "TRUE")
.commit();
if (username.getText().toString().trim().equals("")) {
username.setError(Html
.fromHtml("Please Enter Username"));
username.requestFocus();
} else if (password.getText().toString().trim()
.equals("")) {
password.setError(Html
.fromHtml("Please Enter Password"));
password.requestFocus();
} else {
if (Constants
.checkInternetConnection(WiztangoActivity.this)) {
Constants.userpass = password.getText()
.toString();
new AuthenticData().execute();
} else {
WiztangoBaseApplication.ShowThisDialog("Error",
"Please check internet connection.");
}
if (saveLoginCheckBox.isChecked()) {
prefEditor.putBoolean("saveLogin", true);
prefEditor.putString(Constants.PREF_USERNAME,
username.getText().toString());
prefEditor.putString(Constants.PREF_PASSWORD,
password.getText().toString());
saveLoginCheckBox.setChecked(true);
prefEditor.commit();
} else {
SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove(Constants.PREF_USERNAME);
editor.remove(Constants.PREF_PASSWORD);
editor.commit();
}
}
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
Inbuilt Patterns Provides Email Validation like:
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
emailEditText.setError("Invalid Email");
emailEditText.requestFocus();
}
Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882
It says:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You can use this code for check is Valid Email or not:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Best Approach
Validate email and isEmpty in one method.
public final static boolean isValidEmail(CharSequence target)
{
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
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()) {
isValid = true;
}
return isValid;
}
Try out the below method to validate the Email address.
private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
if (!m_matcher.matches() && editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Try this code:--
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}

Categories

Resources