Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email validation on EditText - 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 protected]", it not run showAlertValidation(); Anything wrong with my code?

like image 363
Michael Julyus Christopher M. Avatar asked Mar 16 '16 15:03

Michael Julyus Christopher M.


People also ask

How to Add email and password Validation in Android studio?

How to validate Email & Password input from EditText before registering user using Android Studio... Email: must contain @ symbol and other general requirements Password: must >6 digits. in your xml, add inputtype attribute to EditText and for password, fetch the it programatically , using 'getText().


3 Answers

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()
like image 108
Salman Nazir Avatar answered Nov 25 '22 05:11

Salman Nazir


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!");
            }
        }
like image 28
joao2fast4u Avatar answered Nov 25 '22 04:11

joao2fast4u


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.

like image 41
Narendra Jadon Avatar answered Nov 25 '22 04:11

Narendra Jadon