I am using the fololowing code to validate the email input
private boolean validateEmail(String email) {
String emailPattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
I execute this on onTextChanged
. The code is below (I am using ButterKnife
)
@OnTextChanged(R.id.et_email)
public void checkCorrectEmail() {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
isValidated = true;
}
}
The issue is that it is not intelligent enough. For an example, if I type myemail@gmail.com
it still show the error message. However if I type myemail@gmail.com
then a space
and clicked delete the space
then everything is fine, error gone.
Formerly this validation was on onClick
of a button. What have I done wrong here?
@OnTextChanged(R.id.et_email)
public void checkCorrectEmail () {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
isValidated = true;
mEditTextEmail.setError(null);
}
}
100% working
Try this :
@OnTextChanged(R.id.et_email)
public void checkCorrectEmail() {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
mEditTextEmail.setError(null)
isValidated = true;
}
}
clear the error on correct input
Use the in-build Email
pattern checker method:
@OnTextChanged(R.id.et_email)
public void checkCorrectEmail () {
if (!Patterns.EMAIL_ADDRESS.matcher(mEditTextEmail.getText().toString()).matches()){
isValidated = false;
mEditTextEmail.setError("Please enter a Valid E-Mail Address!");
mEditTextEmail.requestFocus();
}else {
isValidated = true;
mEditTextEmail.setError(null);
}
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.