You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes we want to validate forms with many fields, for example name, phone, email, and with different rules. If validation fails, we show error message.
We can make simple Validator and Rule
classValidator{func validate(text:String, with rules:[Rule])->String?{return rules.compactMap({ $0.check(text)}).first
}func validate(input:InputView, with rules:[Rule]){
guard let message =validate(text: input.textField.text ??"", with: rules)else{
input.messageLabel.isHidden = true
return}
input.messageLabel.isHidden = false
input.messageLabel.text = message
}}structRule{// Return nil if matches, error message otherwiseletcheck:(String)->String?staticletnotEmpty=Rule(check:{return $0.isEmpty ? "Must not be empty":nil})staticletvalidEmail=Rule(check:{letregex=#"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"#letpredicate=NSPredicate(format:"SELF MATCHES %@", regex)return predicate.evaluate(with: $0) ? nil:"Must have valid email"})staticletcountryCode=Rule(check:{letregex=#"^\+\d+.*"#letpredicate=NSPredicate(format:"SELF MATCHES %@", regex)return predicate.evaluate(with: $0) ? nil:"Must have prefix country code"})}
Sometimes we want to validate forms with many fields, for example name, phone, email, and with different rules. If validation fails, we show error message.
We can make simple
Validator
andRule
Then we can use very expressively
Then a few tests to make sure it works
allSatisfy
To check if all rules are ok, we can use reduce
Or more concisely, use
allSatisfy
The text was updated successfully, but these errors were encountered: