我正在使用fololowing代码验证电子邮件输入
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();
}
我在onTextChanged
执行此操作。代码如下(我正在使用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;
}
}
问题在于它不够聪明。例如,如果我键入myemail@gmail.com
,它仍会显示错误消息。但是,如果我输入myemail@gmail.com
,然后点击space
并点击删除space
,那么一切都很好,错误就消失了。
以前这个验证是在按钮的onClick
上进行的。我在这做错了什么?
答案 0 :(得分:3)
@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%正常工作
答案 1 :(得分:1)
试试这个:
@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;
}
}
清除正确输入错误
答案 2 :(得分:1)
使用内置Email
模式检查器方法:
@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);
}