Validator icon indicating copy to clipboard operation
Validator copied to clipboard

ValidationRuleRequired is not working

Open nrikiji opened this issue 5 years ago • 1 comments

Why is this code valid? How to use Wrong?

 var validationRuleSet = ValidationRuleSet<String?>()
let stringRequiredRule = ValidationRuleRequired<String?>(error: ValidationError(message: "email is required."))
validationRuleSet.add(rule: stringRequiredRule)

let email: String? = nil
let validationResult = Validator.validate(input: email, rules: validationRuleSet)
print(validationResult) // -> valid

nrikiji avatar Nov 05 '18 17:11 nrikiji

True. I've just encountered that too.

Validation only checks if the value is nil or not. But for String type it should check for empty strings too. Since validation uses generics for input types, it is not able to check, because it does not know what type its input is.

For a temporary fix, you can use this in ValidationRuleRequired.swift file

public func validate(input: T?) -> Bool {
      if let input = input as? String {
        return input.count > 0
      }
      return input != nil
}

P.S. Another temporary fix is setting textField's value to nil if it's value is an empty string, using UITextFieldDelegate. For example:

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.text?.count == 0 {
        textField.text = nil
    }
}

If you are using validateOnInputChange; you may use textField(_:shouldChangeCharactersIn:replacementString:) instead

anelad avatar Dec 01 '18 09:12 anelad