Validating UITextField input with text rules

Ernesto Torres
3 min readMay 21, 2017

--

One common escenario when taking input from a user is validating the input is valid. Depending on the business rules this can get quite complicated if there are a lot them.

We can make adding rules cleaner and straightforward, even support a specific error message per rule to display to the user and help them understand why their input is no valid.

Each required text rule can be added using .addTextRule. Each rule has a priority, depending on the order you add them. The first added rule will be the first one applied, then the second rule added and so on.

Each rule has access to the text value from the UITextField and expects a TextRule constructed with two values:

  1. The condition that we are validating
  2. The error related to failing this condition

To add this text rule functionality, RuleBasedTextField is created:

The added features:

  1. An array to keep track of the rules
  2. A function to add new rules
  3. A helper function to evaluate our rules. Returns an error message when one of the rules is not fulfilled. This is helpful to provide an error message to user so they can understand why they input is not valid.
  4. A helper function to check if all the rules are satisfied. For example, can be used to enable a Sign in button.

In our example, we are validating an email with some custom sample rules. For demonstration purposes when there is no error, a message will be displayed to make it clear there is no error generated when applying the rules.

The rules we are going to follow in this example:

  1. At least 4 characters
  2. Must contain “@”
  3. Needs a “.com” domain

Note that for email validation using a Regex is probably a better option. Using this set of rules just for demonstration purposes.

This is the starting state. Rules are evaluated when the keyboard is dismissed by tapping outside the textfield. A textfield with just placeholder text and a label that defaults to No error when there is no error or no input has been entered yet:

For our first input we use 123 which breaks the first rule requiring at least 4 characters:

Then when that rule is fullfilled, the next rule validated is the input contains the “@” character:

And finally a rule requiring “.com”:

When all the rules are fullfilled a “No Error” message is displayed:

This rule-based text validation allows to add, modify or replace text rules in a single place and keep all your text input business rules together.

You can view all the code at once here.

--

--

Ernesto Torres

Software developer, Game maker and sometimes Artist. My opinions are my own.