LinusG.
LinusG.

Reputation: 28982

Validatable - multiple rules for single field

I have these Validatable rules on my User model for user creation:

extension User.Create: Validatable {
    static func validations(_ validations: inout Validations) {
        validations.add("email", as: String.self, is: .email)
        validations.add("password", as: String.self, is: .count(8...))
    }
}

Now, I want to allow the user to create an account without a password, in which case the password will be auto-generated. (User.Create.password is an optional now.)
But if they do provide a password, it should be validated as shown above.

Is that possible with Validatable or do I need to manually validate in the request?

Upvotes: 1

Views: 44

Answers (1)

LinusG.
LinusG.

Reputation: 28982

You can simply extend your ruleset for the password validation by .empty:

validations.add("password", as: String.self, is: .count(8...) || .empty)

That way, the field still needs to be present in the request, but it can be empty.

Upvotes: 1

Related Questions