
親,我的簡書已不再維護和更新了,所有文章都遷移到了我的個人博客:https://mikefighting.github.io/,歡迎交流。
服務(wù)端在有數(shù)據(jù)請求時需要對數(shù)據(jù)進行校驗然后返回響應(yīng)的校驗結(jié)果,比如要求必須輸入郵箱,必須輸入電話等,Validation工具給我們提供了非常方便的常用操作,接下來就對其使用過程做以總結(jié)(本文用到的是Validation 1.2.0版本)。
Vapor中添加Validation依賴包
在Package.swift文件中添加如下的依賴,比如:
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
.Package(url: "https://github.com/vapor/validation-provider.git", majorVersion: 1)
之后要執(zhí)行
vapor clean或者rm -rf .build Package.pins,然后執(zhí)行vapor update或者swift package update,這樣才可以安裝好依賴。
校驗實例
Alphanumeric校驗
接下來我們來做一個簡單的校驗,校驗輸入的字符串是否是a-z或者0-9在請求中加入如下代碼:
get("alpha") { request in
guard let input = request.data["input"]?.string else {
throw Abort.badRequest
}
let validInput = try input.tested(by: OnlyAlphanumeric())
return "validated:\\(validInput)"
}
我們運行程序,然后在PostMan中輸入http://localhost:8080/alpha?input=example@github.com,這時會得到下面的返回值:
{"identifier":"Validation.ValidatorError.failure","reason":"Internal Server Error","debugReason":"OnlyAlphanumeric failed validation: example@github.com is not alphanumeric","error":true}
這也就說明了,我們傳輸?shù)膯柋緝?nèi)容不符合alphanumeric。
然后我們將URL改為http://localhost:8080/alpha?input=example123,然后就會看到我們的返回值
validated:example
郵箱校驗
我們可以利用EmailValidator來做郵箱的校驗,方法同上面一樣:
get("email") { request in
guard let input = request.data["input"]?.string else {
throw Abort.badRequest
}
let validaInput = try input.tested(by: EmailValidator())
return "validated:\\(validaInput)"
}
然后我們輸入URL:http://localhost:8080/email?input=wallaceicdi@outlook.com,然后就會的到:
Validated: wallaceicdi@outlook.com
其余自帶校驗工具
| 校驗類 | 功能 | 用法 |
|---|---|---|
| Unique | 輸入內(nèi)容是否唯一 | someCharacter.tested(by: Unique()) |
| Compare | 輸入內(nèi)容的數(shù)值比較 | int.tested(by:Compare.greaterThan(1)) |
| Contains | 輸入的內(nèi)容是否包含某個 | someArray.tested(by: Contains("1")) |
| Count | 輸入的內(nèi)容個數(shù) | someArray.tested(by: Count.max(2)) |
| Equals | 輸入的內(nèi)容是否相同 | someConent.tested(by: Equals.init("equal")) |
| In | 輸入內(nèi)容是否被包含 | input.tested(by: In.init(["1","2","3"])) |
創(chuàng)建自己的校驗工具
通過參考工具自帶的Equals.Swift:
/// Validates that matches a given input
public struct Equals<T>: Validator where T: Validatable, T: Equatable {
/// The value expected to be in sequence
public let expectation: T
/// Initialize a validator with the expected value
public init(_ expectation: T) {
self.expectation = expectation
}
public func validate(_ input: T) throws {
guard input == expectation else {
throw error("\\(input) does not equal expectation \\(expectation)")
}
}
}
從這里面我們可以看出,只要遵守Validator協(xié)議,并且實現(xiàn)其validate方法即可。