Skip to content
This repository has been archived by the owner on Jul 21, 2020. It is now read-only.

ValidationRuleRequired is not working #113

Open
nrikiji opened this issue Nov 5, 2018 · 1 comment
Open

ValidationRuleRequired is not working #113

nrikiji opened this issue Nov 5, 2018 · 1 comment

Comments

@nrikiji
Copy link

nrikiji commented Nov 5, 2018

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
Copy link

anelad commented Dec 1, 2018

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants