Validation

This commit is contained in:
Gwendal Roué committed 2015-08-23 14:57:17 +02:00
1 parent 4ec2964ddf
commit 9ee0d200ac
1 file changed
+36
+36
View File
@@ -980,9 +980,11 @@ RowModel methods can throw [DatabaseError](#error-handling) and also specific er
Based on those facts, here are a few hints:
- [Autoincrement](#autoincrement)
- [Validation](#validation)
- [Default Values](#default-values)
- [INSERT OR REPLACE](#insert-or-replace)
#### Autoincrement
**For "autoincremented" ids**, declare your id column as INTEGER PRIMARY KEY, and declare a RowID primary key:
@@ -1025,6 +1027,40 @@ person.id // some value
```
#### Validation
RowModel does not provide any built-in validation.
You can use some external library such as [GRValidation](https://github.com/groue/GRValidation) in the update() and insert() methods:
```swift
class Person : RowModel, Validable {
var name: String?
override func update(db: Database) throws {
// Validate before update
try validate()
try super.update(db)
}
override func insert(db: Database) throws {
// Validate before insert
try validate()
try super.insert(db)
}
func validate() throws {
// Name should not be nil
try validate(property: "name", with: name >>> ValidationNotNil())
}
}
// fatal error: 'try!' expression unexpectedly raised an error:
// Invalid <Person name:nil>: name should not be nil.
try! Person(name: nil).save(db)
```
#### Default Values
**Avoid default values in table declarations.** RowModel doesn't know about them, and those default values won't be present in a row model after it has been inserted.