Form validation library for Android?

后端 未结 7 2124
自闭症患者
自闭症患者 2020-12-09 09:48

Is there any mature form validation API / library for Android? I\'ve found http://code.google.com/p/android-binding/ but it seems that is under heavy development.

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 10:47

    The library now supports annotations, you can validate your fields just by adding them. Here is an example code snippet.

    @NotEmpty
    @Order(1)
    private EditText fieldEditText;
    
    @Checked(message = "You must agree to the terms.")
    @Order(2)
    private CheckBox iAgreeCheckBox;
    
    @Length(min = 3, message = "Enter atleast 3 characters.")
    @Pattern(regex = "[A-Za-z]+", message = "Should contain only alphabets")
    @Order(3)
    private TextView regexTextView;
    
    @Password
    @Order(4)
    private EditText passwordEditText;
    
    @ConfirmPassword
    @Order(5)
    private EditText confirmPasswordEditText;
    

    The order annotation is optional and specifies the order in which the fields should be validated. This is ONLY required if you want the order of the fields to be preserved during validation. There are also other annotations such as @Email, @IpAddress, @Isbn, etc.,

    Android Studio / Gradle

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

    Check for the latest available version.

    Eclipse
    You can download the jar from here and add it to your Android libs directory.

    Old Answer (Saripaar v1)
    I have authored a library for validation. Here is the associated blog and the project. I have sucessfully used it in production applications and it currently satisfies most of the common scenarios that we face in validation forms for Android. There are rules that come out of the box and if you need to write your own, you can do that by writing your own Rule.

    Here is a snippet that illustrates the use of the library.

    validator.put(nameEditText, Rules.required("Name is required."));
    validator.put(nameEditText, Rules.minLength("Name is too short.", 3));
    validator.put(emailEditText, Rules.regex("Email id is invalid.", Rules.REGEX_EMAIL, trim));
    validator.put(confirmPwdEditText, Rules.eq("Passwords don\'t match.", pwdEditText);
    

    There are also or and and rules that allow you to perform && and || operations on several rules. There is also a compositeOr and compositeAnd rule that allows you to perform validations between several Views.

    If any of those seem to be insufficient, you can always write your own rule by extending the Rule class.

提交回复
热议问题