Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Custom Validator section to Validation docs #935

Merged
merged 8 commits into from
Nov 9, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add Custom Validator section to Validation docs
  • Loading branch information
hsharghi committed Nov 6, 2023
commit 12b9ad6fbf22068732733e8c79c41cc67b0f59b4
62 changes: 62 additions & 0 deletions docs/basics/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,65 @@ Validators can also be combined to build complex validations using operators.
|`!`|prefix|Inverts a validator, requiring the opposite.|
|`&&`|infix|Combines two validators, requires both.|
|`||`|infix|Combines two validators, requires one.|



## Custom Validator



To create a custom validator for validating a zip code, Here is the steps:

First let's create a struct to for `ZipCode` validator.

```swift
extension ValidatorResults {
/// `ValidatorResult` of a validator that validates whether a `String` is a valid zip code.
public struct ZipCode {
/// The input is a valid zip code
public let isValidZipCode: Bool
}
}
```
Next, comform the `ZipCode` to `ValidatorResult`

```swift
extension ValidatorResults.ZipCode: ValidatorResult {
public var isFailure: Bool {
!self.isValidZipCode
}

public var successDescription: String? {
"is a valid zip code"
}

public var failureDescription: String? {
"is not a valid zip code"
}
}
```
Finally let's write the validation logic
```swift
private let zipCodeRegex: String = "^\\d{5}(?:[-\\s]\\d{4})?$"

extension Validator where T == String {
/// Validates whether a `String` is a valid zip code.
public static var zipCode: Validator<T> {
.init {
guard
let range = $0.range(of: zipCodeRegex, options: [.regularExpression]),
range.lowerBound == $0.startIndex && range.upperBound == $0.endIndex
else {
return ValidatorResults.ZipCode(isValidZipCode: false)
}
return ValidatorResults.ZipCode(isValidZipCode: true)
}
}
}
```

Now we can use it

```swift
validations.add("zipCode", as: ZipCode.self, is: .zipCode, required: true)
```