Class DS.Errors
Holds validation errors for a given record organized by attribute names.
Every DS.Model has an errors
property that is an instance of
DS.Errors
. This can be used to display validation error
messages returned from the server when a record.save()
rejects.
This works automatically with DS.ActiveModelAdapter
, but you
can implement ajaxError
in other adapters as well.
For Example, if you had an User
model that looked like this:
app/models/user.js | |
1 2 3 4 5 6 |
import DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string') }); |
And you attempted to save a record that did not validate on the backend.
1 2 3 4 5 |
var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save(); |
Your backend data store might return a response that looks like this. This response will be used to populate the error object.
1 2 3 4 5 6 |
{ "errors": { "username": ["This username is already taken!"], "email": ["Doesn't look like a valid email."] } } |
Errors can be displayed to the user by accessing their property name to get an array of all the error objects for that property. Each error object is a JavaScript object with two keys:
message
A string containing the error message from the backendattribute
The name of the property associated with this error message
You can also access the special messages
property on the error
object to get an array of all the error strings.