All of the user input we have been validating thus far had rules that were all required to pass in order for the input to be valid. A password had to have a lowercase letter and an uppercase letter and a number.
There are many scenarios in which you may only need some combination of the validators to pass in order for the input to be considered valid. For example: perhaps you have a field for a phone number that is optional. If they enter a phone number, you want to make sure it’s the correct number of digits, correct characters, etc. However, if they don’t enter anything at all, that is also valid.
You want the phone number to be valid or an empty phone number.
The example I’m going to show will expand upon the password validator, since by now you are familiar with that and more importantly I am lazy.
As a refresh on the requirements for passwords, they:
Must not be empty
Must be at least 8 characters long
Must have one uppercase letter, lowercase letter and a number
I’m going to expand that last rule to be:
Must have one uppercase letter
Must have one lowercase letter
Must have either a number or a special character
And Composite Validator
What we were previously calling CompositeValidator I am just going to rename to AndCompositeValidator.
Or Composite Validator
For this one, if any of the validators passed in return a valid result, than the OrCompositeValidator will return that the input is valid. Otherwise, every error will be returned in the array with the invalid response.
This is just a class I use to instantiate validators.
I didn’t bother showing the special character validator. It’s very similar to the others, just different regex.
There are many modifications and additions that can be added to this pattern to make it more powerful and fit the needs of an application. To get more ideas, you can look at Microsoft’s specification pattern, which is what a lot of this is based on.
This is going to end my series on composite validators. Hope you found it interesting. Tag me on twitter or email me with any feedback!