-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from Skyback/master
UniqueFieldValidator and RegexValidator
- Loading branch information
Showing
3 changed files
with
124 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import Vapor | ||
import Fluent | ||
|
||
/** | ||
Validates if the value exists on the database | ||
*/ | ||
public class UniqueFieldValidator<ModelType: Entity>: FieldValidator<String> { | ||
let column: String | ||
let additionalFilters: [(column:String, comparison:Filter.Comparison, value:String)]? | ||
let message: String? | ||
public init(column: String, additionalFilters: [(column:String, comparison:Filter.Comparison, value:String)]?=nil, message: String?=nil) { | ||
self.column = column | ||
self.additionalFilters = additionalFilters | ||
self.message = message | ||
} | ||
public override func validate(input value: String) -> FieldValidationResult { | ||
// Let's create the main filter | ||
do { | ||
let query = try ModelType.query() | ||
try query.filter(self.column, value) | ||
// If we have addition filters, add them | ||
if let filters = self.additionalFilters { | ||
for filter in filters { | ||
try query.filter(filter.column, filter.comparison, filter.value) | ||
} | ||
} | ||
// Check if any record exists | ||
if(try query.count() > 0){ | ||
return .failure([.validationFailed(message: message ?? "Value \(self.column) must be unique.")]) | ||
} | ||
// If not we have green light | ||
return .success(Node(value)) | ||
} catch { | ||
return .failure([.validationFailed(message: message ?? "Value \(self.column) must be unique.")]) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters