Tackling Regex – Value cannot start or end with space, but can contain spaces and selected characters, up to max length

But I needed to update a form field regex validation, so I tackled it head-on and won.

As a side note, regular expression creation is also one of the best examples of where Test Driven Development (TDD) works well. You really cannot create or maintain a regex without having all the test cases written first.

Validation Requirements

For a value entered in the field, it:

Cannot start with a space.

Cannot end with a space.

May contain a one or more sapces (surrounded by other allowed characters).

May also contain the following characters: A-Z, a-Z, 0-0, “-“, “_”, “\”, “/”.

If a value is entered in the field the total character count may be from 1 to 20 characters.