overview
Validity is an important concept in Dream, since it can invalidate a record before saved, which prevents the record from being saved. To determine if a record is valid, Dream provides some useful helpers:
isValid / isInvalid
export default class User extends ApplicationModel {
...
@deco.Validates('contains', '@')
public email: string
}
const user = User.new({ email: 'invalid-email' })
console.log(user.isValid) // false
console.log(user.isInvalid) // true
user.email = 'valid@email'
console.log(user.isValid) // true
console.log(user.isInvalid) // false
A failed validation is recorded in the record's errors, keyed by column, under the name of the validation that failed:
const user = User.new({ email: 'invalid-email' })
user.isInvalid // true
user.errors.email // ['contains']
Several @deco.Validates decorators can be stacked on one property, and each one that fails adds its name. A custom validator adds the message it passes to addError.
If a save is attempted against a record, each of its validations will be called. If any of the validations fail, an exception will raise which prevents the record from being saved. When Psychic intercepts this error, it responds with a bare 400 and no body. To show the field-level errors to the client, check isInvalid before saving and return them yourself with this.badRequest({ errors: record.errors }) — see Surfacing field-level validation errors.
Built-in validators
For anything these don't cover, write a custom validator.
A non-optional BelongsTo association is validated for its presence automatically — Dream registers a requiredBelongsTo validation for you. Never declare @deco.Validates('requiredBelongsTo') yourself. See BelongsTo — a required association is a two-way non-nullable contract.