Vapor

Vapor系列教程 - Validation

2016-09-06  本文已影响102人  CaryZheng

Vapor 提供了一种机制来验证数据的合法性。

基本用法


验证 Employee 的 email 和 name 数据是否合法

class Employee {
    var email: Valid<Email>
    var name: Valid<Name>

    init(request: Request) throws {
        email = try request.data["email"].validated()
        name = try request.data["name"].validated()
    }
}

通过声明 Valid<> 类型来保证数据的合法性,只有通过验证的数据才能传递给 emailname

只需使用 .validated() 进行数据验证, 而request.data 返回的数据类型均可调用 .validated()

这里, Email 是 Vapor 内置的 validator ,而 Name 不是。

Valid<OnlyAlphanumeric>
Valid<Email>
Valid<Unique<T>>
Valid<Matches<T>>
Valid<In<T>>
Valid<Contains<T>>
Valid<Count<T>>

Name 实现

class Name: ValidationSuite {
    static func validate(input value: String) throws {
        let evaluation = OnlyAlphanumeric.self
            && Count.min(5)
            && Count.max(20)

        try evaluation.validate(input: value)
    }
}

只有纯字母且字数介于 5~20 之间的名字才能通过验证。

使用示例

drop.post("validation") { request in
    do {
        let employee = try Employee(request: request)
        
        print("employee name : \(employee.name.value)")
        print("employee email : \(employee.email.value)")
    } catch let error as ValidationError<Email> {
        return "Email is invalid"
    } catch let error as ValidationError<Name> {
        return "Name is invalid"
    }
    
    return "validation success"
}

只有传入的 nameemail 数据均合法才能通过验证,不然将会抛出异常。

除了通过 validated ,还有其他两种方式验证

    let text = "test123"
    let result1 = text.passes(Count.min(5))
    let result2 = try text.tested(by: Count.min(5))
    
    print("result1 = \(result1)")
    print("result2 = \(result2)")

输出

result1 = true
result2 = test123

passes 方法返回 Bool 类型, 而 tested 方法返回原始类型。


Go to Vapor系列教程 - 目录

上一篇 下一篇

猜你喜欢

热点阅读