最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Validatable - multiple rules for single field - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Mar 11 at 12:37 LinusG. asked Mar 11 at 12:11 LinusG.LinusG. 29.1k31 gold badges124 silver badges183 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论