我有以下片段使用Saaripar的注释来验证某些字段:
/**
* Simple fragment used to register a new user
*/
public static class FragmentRegister extends Fragment implements Validator.ValidationListener {
@InjectView(R.id.display_name_label)
TextView displayNameLabel;
@NotEmpty(messageResId = R.string.validation_not_empty)
@InjectView(R.id.display_name)
EditText displayName;
@InjectView(R.id.username_label)
TextView nameLabel;
@NotEmpty(messageResId = R.string.validation_not_empty)
@InjectView(R.id.username)
EditText username;
@InjectView(R.id.password_label)
TextView passwordLabel;
@InjectView(R.id.password)
@Password
@Size(min = 6, messageResId = R.string.validation_6_characters)
EditText password;
@InjectView(R.id.confirm_password_label)
TextView confirmPasswordLabel;
@InjectView(R.id.confirm_password)
@ConfirmPassword
EditText confirmPassword;
@InjectView(R.id.create_user_button)
Button createUserButton;
private Validator validator;
public FragmentRegister() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_register, container, false);
// Set up Saripaar validator
validator = new Validator(this);
validator.setValidationListener(this);
// Injecting views with ButterKnife
ButterKnife.inject(this, rootView);
return rootView;
}
...
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
// Injected view listeners
@OnClick(R.id.create_user_button)
public void createUser() {
validator.validate();
}
// Saripaar callbacks
@Override
public void onValidationSucceeded() {
clearErrors();
String dispName = displayName.getText().toString();
String user = username.getText().toString();
String pass = password.getText().toString();
Controller.instance().register(user, dispName, pass);
getActivity().finish();
}
@Override
public void onValidationFailed(List<ValidationError> errors) {
clearErrors();
View view = null;
for (ValidationError error : errors) {
view = error.getView();
if (view instanceof EditText) {
((EditText) view).setError(error.getFailedRules().get(0).getMessage(getActivity()));
}
}
if(view != null) {
view.requestFocus();
}
}
public void clearErrors() {
displayName.setError(null);
username.setError(null);
password.setError(null);
confirmPassword.setError(null);
}
}
@ConfirmPassword
永远不起作用,它只会在@Password
字段显示一条空错误消息,并为@ConfirmPassword
显示"密码不匹配"。知道会发生什么吗?
https://github.com/ragunathjawahar/android-saripaar/issues/52 似乎这是一个错误,今天将修复。
尝试在确认密码字段中添加一条消息,例如
@InjectView(R.id.confirm_password)
@ConfirmPassword(order = 6, message = "Password mismatch")
EditText confirmPassword;