5步学会表单验证框架android-saripaar的使用

梁丘兴腾
2023-12-01

github地址:https://github.com/ragunathjawahar/android-saripaar

1,添加依赖

compile 'com.mobsandgeeks:android-saripaar:2.0.3'

2,为组件添加注解,例如:

    @Order(1)
    @NotEmpty(message = "用户名不能为空")
    @Length(min=6,max=12,message = "用户名6~12位之间")
    @Pattern(regex = "^\\w+$",message = "仅可输入数字 字母 下划线")
    @BindView(R.id.userName)
    EditText userName;
    @NotEmpty(message = "密码不能为空")
    @Password(min=6,message = "密码最少为6位")
    @Order(2)
    @BindView(R.id.passWord)
    EditText password;
    @NotEmpty(message = "确认密码不能为空")
    @ConfirmPassword(message = "两次密码输入不一致")
    @Order(3)
    @BindView(R.id.passWord2)
    EditText password2;
    @NotEmpty(message = "姓名不能为空")
    @Order(4)
    @BindView(R.id.name)
    EditText name;
    @NotEmpty(message = "手机号码不能为空")
    @Order(5)
    @BindView(R.id.phone)
    EditText phone;
    @NotEmpty(message = "验证码不能为空")
    @Length(min = 4,max = 4,message = "验证码为4位")
    @Order(6)
    @BindView(R.id.code)
    EditText code;
    @Order(7)
    @Checked(message = "必须接受声明条款")
    @BindView(R.id.checkbox)
    CheckBox checkbox;

提供几种正则示例:

String only_Chinese="^[\\u4e00-\\u9fa5]{0,}$";  // 仅可以输入中文
String only_number="^[0-9]*$"; // 仅可以输入数字
String number_letter_underline="^\\w+$"; // 数字,字母,下划线
String email="\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}"; // 邮箱验证
String phone="^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$"; // 手机号码验证

更多正则表达式写法参见博客:https://www.cnblogs.com/go4mi/p/6426215.html
更多验证规则,比如数字最大值,数字最小值,金钱最大值,金钱最小值等,详情查看:https://github.com/ragunathjawahar/android-saripaar/tree/master/saripaar/src/main/java/com/mobsandgeeks/saripaar/annotation

3,在onCreate方法中初始化:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Code…

    validator = new Validator(this);
    validator.setValidationListener(this);

    // More code…
}

4,实现ValidationListener接口:

public class RegistrationActivity extends Activity implements ValidationListener {

    // Code…

    @Override
    public void onValidationSucceeded() {
        // 全部通过验证
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);
            // 显示上面注解中添加的错误提示信息
            if (view instanceof EditText) {
                ((EditText) view).setError(message);
            } else {
                // 显示edittext外的提示,如:必须接受服务协议条款的CheckBox
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            }
        }
    }
}

5,在注册按钮的点击事件中,执行验证操作:

registerButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        validator.validate();
    }
});
 类似资料: