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:

The actual format is:

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.

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:

And this is how the filter looks:

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.

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