Android Studio中的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 {

通过添加^和$来指定字符串的开始和结束位置。试试看:

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

现在,只有当名字包含一些特殊或数字字符时,才应该得到错误消息。

最新更新