Input validation in Android

I was trying to enforce a input format and then validate the input data before submitting it in a post to our api.

In the code samples below I’m using a Rx Observer “idValidObs” that observes a EditText “idEditText”.

The input format I’m trying to match can be described by this regexp:

String inputIdFormatRegex = "^\\d{0,4}$|^\\d{4}-\\d{0,4}$|^\\d{4}-\\d{4}-\\d{0,4}$";

The actual format is:

String actualIdFormatRegex = "^\\d{4}-\\d{4}-\\d{4}$";

And for those who are not familiar with regex syntax this translates to xxxx-xxxx-xxxx where x is a digit in the range 0-9. The main difference between the input and actual format is that the input must return match for every step on the way when typing the id in the idEditText or we would flag for errors incorrectly while the user is typing.

To validate the id before posing it I’m using the actualFormatRegex and a simple .matches call on the id string.

Observable<Boolean> idValidObs = id.doOnNext(text -> {
    boolean ok = text.matches(idFormatRegex);
    // if ok != true, show error message
}).map(z -> true);

To enforce the format while the user is typing we use the other regex (inputIdFormatRegex) in a InputFilter. To use a InputFilter we just create a instance of it and set it on out EditText like so:

idEditText.setFilters(new InputFilter[]{new IdInputFilter()});

And this is how the filter looks:

public class IdInputFilter implements InputFilter {
    Pattern mPattern;

    public IdInputFilter() {
        mPattern = Pattern.compile(idFormatRegex);

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        Matcher matcher = mPattern.matcher(dest);
        if (!matcher.matches())
            return "";
        return null;

The filter is quite simple, it just runs whatever code we put in the filter method for each change of the EditText and then returns null if we accept the change to the EditText text data or a string to use instead of the change made bu the user if we are not happy with the change. So by rejecting al changed that does comply with a certain regex we can enforce the format while the user is typing. The hard part here was to figure out how to combine the InputFormater with a regex that works for al the steps of inputing the id.

This Post Has 2 Comments

  1. Sebastian

    Could you please double check the code samples? Is a glue part missing?

  2. Carl-Emil Kjellstrand

    Any part in particular you are wondering about? Its not a complete cut n paste example and was not ment to be, for that i would recommend stackoverflow :)

Leave a Reply