Android Form Field Validation

?p=138

A simple method for the validation of your Form values in Android.

Read More...

Validation ??

After coding a while for the Android platform, I was getting annoyed that there was no default validation support (i.e that I could find) for the validation of EditText, CheckBox etc fields.
Therefore I have written a small set of interfaces/Classes that gives you and me the possibility to do the validation you need.

The basics

To be able to use the validation you need to implement de Validator Interface and extend the AbstractValidator class. In the abstract class a couple of handy methods are already implemented, but may be overridden for your specific usage.
An example of an implemented validator:

package nl.android.validator;

import android.widget.CheckBox;

/**
 * A Checkbox required field
 * implementation of the validator.
 * With this validator a checkbox can be tested
 * for the required option.
 *
 * @author http://nl.linkedin.com/in/marcdekwant
 *
 */

public class CheckBoxRequiredValidator extends AbstractValidator {

  private CheckBox _source;

  /** CONSTRUCTORS */

  public CheckBoxRequiredValidator(CheckBox source) {
    super(true);
    _source = source;
  }

  public CheckBoxRequiredValidator(CheckBox source, String requiredMessage) {
    super(true);
    _source = source;
    _requiredMessage = requiredMessage;
  }

  @Override
  public ValidationResult validate() {
    ValidationResult _v = super.validate();
    if (_v==null) {
      if (_source.isChecked()) {
        _v = new ValidationResult(true, "");
      } else {
        _v = new ValidationResult(false, _requiredMessage);
      }
    }
    return _v;
  }

  @Override
  public Object getSource() {
    return _source;
  }

}

Example usage in a activity

       .....
      private List<validator> validators = new ArrayList<validator>();
      .....
      private void someMethod() {
          validators.add(new CheckBoxRequiredValidator(myCheckbox, "This checkbox is required"));
      }
      .....
      private void myAcceptMethod() {
         List<validationResult> _validationResults = AbstractValidator.validateAll(validators);
       if (_validationResults.size()==0) {
              // Validation is succesfull
         }
      }

Source code

Android Validation zip

Kind regards,

Marc

This entry was posted in Android, Interaction, Java, Validation and tagged , , . Bookmark the permalink. Comments RSS feed for this post. Post a comment or leave a trackback: Trackback URL.