大家好,我已经添加了这行代码进行验证,以检查名字字段是否包含数字或特殊字符但是,在测试它时,似乎firstname总是显示错误 任何人都可以帮助。非常感谢!
(!isNetworkAvailable()) {
showSweetDialog(AppConstants.ERR_CONNECTION, "error", false, null, null);
} else if (firstName.isEmpty()) {
setError(etFirstName, AppConstants.WARN_FIELD_REQUIRED);
}
else if(!firstName.matches("[a-zA-Z]")){
setError(etFirstName, AppConstants.WARN_FIELD_REQUIRED);
}
else if (lastName.isEmpty()) {
setError(etLastName, AppConstants.WARN_FIELD_REQUIRED);
} else if (mobile.isEmpty()) {
setError(etMobile, AppConstants.WARN_FIELD_REQUIRED);
} else if (email.isEmpty()) {
setError(etEmail, AppConstants.WARN_FIELD_REQUIRED);
} else if (password.isEmpty()) {
setError(etPassword, AppConstants.WARN_FIELD_REQUIRED);
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
setError(etEmail, AppConstants.WARN_INVALID_EMAIL_FORMAT);
} else if (address.isEmpty()) {
setError(etAddress, AppConstants.WARN_FIELD_REQUIRED);
} else {
答案 0 :(得分:1)
通过添加^和$来指定字符串的开头和结尾的位置。试试吧:
else if(!firstName.matches("^[A-Za-z]+$")){
setError(etFirstName, AppConstants.WARN_FIELD_REQUIRED);
}
表示:
^ beginning of the string,
[A-Za-z] search for alphabetical chars either they are CAPITALS or not
+ string contains at least one alphabetical char
$ end of the string
现在,只有当名字包含一些特殊或数字字符时,才会收到错误消息。