android-form-validator
ShabanKamell
27
Visit GitHub Repo
Validation

FormValidator for Android

Powerful, simple and customizable EditText validator for Android.

Install

Gradle:

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

dependencies {
	        implementation 'com.github.ShabanKamell:FormValidator:1.0.0'
}

Usage

<com.sha.formvalidator.widget.FormEditText
    android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_phone"
    android:inputType="phone"
    app:validationType="phone" />

And validate the field in your code:

    FormEditText phoneField = findViewById(R.id.et);
    if (phoneField.validate()){
	// phone is valid
    } else {
    // phone isn't valid
    }

Validation Types

Validation type can be set with validationType attribute like the previous example app:validationType="phone" Note: required is the default validation type. f you don't specify any one

Type Description Required attributes
required validates required fields _
numeric validates numeric only _
alpha validates alpha only _
alphaNumeric validates alpha numeric _
email validates email _
creditCard validates credit card
using Luhn Algorithm
_
phone validates phone _
domainName validates domain name _
ipAddress validates IP address _
webUrl validates web URL _
personName validates person name _
personFullName validates person full name _
regex validates a REGEX - regex
numericRange validates numeric range - minNumber
- maxNumber
floatNumericRange validates floating-point ranges - floatMinNumber
- floatMaxNumber
date validates date - dateFormat

Other Attributes

Attribute Description
errorMessage message if the field is invalid
requiredErrorMessage message if the field is empty
customValidationType a string for custom validation
(see usage below)

Custom Validators in XML

FormValidator is very flexible. It's support any custom validator. Just extend CustomValidator and specify a unique constant to be used as a custom validation type:

public class NumberOneCustomValidator extends CustomValidator {  
  
    public NumberOneCustomValidator(String errorMessage) {  
        super(errorMessage);  
    }  
    @Override  
    public String customValidationType(Context context) {
    // define a unique constant to be used in XML with customValidationType
        return context.getString(R.string.custom_validator_number_one);  
    }  
    @Override  
    public boolean isValid(EditText et) {
        return et.getText().toString().equals("1");  
    }  
}

To use NumberOneCustomValidator in XML put this line:

<com.sha.formvalidator.widget.FormEditText
  ...
    app:customValidationType="@string/custom_validator_number_one" 
    />

And tell FormValidator about the validator before starting validation

Validators.customValidators = Arrays.asList(  
        new NumberOneCustomValidator("Value doesn't equal 1") 
);

Custom Validators Best Practices

  • DON'T hard-code the type app:customValidationType="customType"
  • Add custom code as a non-translatable string in a separate value file
<!-- defined in custom_validators.xml -->
<string name="custom_validator_number_one" translatable="false">NumberOne</string>

and refer to it as a string as the previous example in custom validator and XML. Note defining the custom like this prevents changing the value by mistake.

  • The best place to define cusom validators is Application class
public class App extends Application {  
  @Override  
  public void onCreate() {  
        super.onCreate();  
        Validators.customValidators = Arrays.asList(  
                new NumberOneCustomValidator("Value doesn't equal 1") // use    context.getString() in production  
        );  
  }  
}

Custom Validators in Code

To add a custom validator in code just implement Validator interface

public class SuffixValidator extends Validator {  
    private String suffix;  
    
    public SuffixValidator(String suffix, String errorMessage) {  
        super(errorMessage);  
       this.suffix = suffix;  
    }  
  
    public boolean isValid(EditText et) {  
        return et.getText().toString().endsWith(suffix);  
    }  
}

Usage

formEditText.addValidator(new SuffixValidator(/* suffix*/"d", /* error*/"Must start with d."));

Note SuffixValidator is predefined in the library.

Multiple Fields Validation

For easy multiple fields validation, you can use FormValidator `

findViewById(R.id.btnJustCheck).setOnClickListener(__ -> {  
    boolean isValid = new FormValidator(etAllowEmpty, etAlpha, etPhone).isValid();  
    toast("Just check result: " + isValid);
});

// OR

new FormValidator(etAllowEmpty, etAlpha, etPhone)  
        .validateOnClick(  
                findViewById(R.id.btnValidateOnClick),  
                isValid -> toast("Validate on Click result: " + isValid)  
        );

RX

Instead of the previous imperative code, you can use RxFormValidator

findViewById(R.id.btnJustCheck).setOnClickListener(__ -> {  
     new RxFormValidator(etAllowEmpty, etAlpha, etPhone)  
            .validate()  
            .subscribe(isValid -> toast("Just check result: " + isValid));
});

// OR

new RxFormValidator(etAllowEmpty, etAlpha, etPhone)  
        .validateOnClick(findViewById(R.id.btnValidateOnClick))  
        .subscribe(isValid -> toast("Validate on Click result: " + isValid));

AutoCompleteTextView

You can use FormAutoCompleteTextView with complete validation support

FormAutoCompleteTextView autoCompleteTv = findViewById(R.id.autoCompleteTv);  
if (autoCompleteTv.validate()) {  
    Toast.makeText(this, "Valid", Toast.LENGTH_LONG).show();  
}

FormEditTextPreference

You can use FormEditTextPreference for validating EditTextPreference

    <com.sha.formvalidator.widget.FormEditTextPreference
        android:ems="10"
        android:hint="@string/phone_number_hint"
        android:inputType="phone"
        android:key="phone_number"
        android:maxLines="1"
        android:selectAllOnFocus="true"
        android:title="@string/phone_number_label"
        app:required="true"
        app:validationType="phone" />

See 'app' module for the full code.

License

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Credit

Android Form EditText.

Become Pro in Android by watching videos

OUR LEARNERS WORK AT