简体   繁体   中英

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@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.

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

在使用 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();
                               }
                        }
                }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM