Validating data is usually one of the "chores" we encounter while building apps. It can be annoying and boring code to write, and can be a huge source of bugs. Today we'll check out a great library called FormValidatorSwift that can help us avoid all these issues. Let's take a look.
The core of FormValidatorSwift is built around checking if a String
passes some sort of test to be deemed 'valid'.
We'll use individual Conditions
or combined sets of Conditions
called Validators
. We'll attach these to controls like Text Fields and Text Views to allow them to be validated.
Let's try out the included ValidatorTextField
to validate an email address:
let field = ValidatorTextField(validator: EmailValidator())
Then, we'll configure it to allow the user to begin entering an email address that's invalid like "hello@"
, and specify that it should only be validated when it loses focus.
field.shouldAllowViolation = true
field.validateOnFocusLossOnly = true
This sets us up perfectly for our final steps: Displaying the validation info.
First, we'll set the validatorDelegate
:
field.validatorDelegate = self
Then, we'll implement one function to update the visual state of our field when the validation state changes:
func validatorControl(validatorControl: ValidatorControl, changedValidState validState: Bool) {
guard let view = validatorControl as? UIView else { return }
if validState {
view.backgroundColor = UIColor.white
errorLabel.hidden = true
} else {
view.backgroundColor = UIColor.red
errorLabel.hidden = false
}
}
And finally, we'll add one more function to display the actual reason that validation failed (if it failed):
func validatorControl(validatorControl: ValidatorControl, violatedConditions conditions: [Condition]) {
var errorText = ""
for condition in conditions {
errorText += condition.localizedViolationString
}
errorLabel.text = errorText
errorLabel.hidden = false
}
Last but not certainly not least, we can group our fields into a provided Form
type, then ask if the whole thing is valid:
var form = ControlForm()
form.addEntry(field)
form.addEntry(anotherField)
print(form.isValid) // true
Learn more about FormValidatorSwift at git.io/formvalidator