adamwaite / Validator

Drop in user input validation for your iOS apps.
MIT License
1.42k stars 218 forks source link

ValidationRuleRequired is not working #113

Open nrikiji opened 5 years ago

nrikiji commented 5 years ago

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
anelad commented 5 years ago

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