Skip to content

Commit e100b17

Browse files
committed
Added an example adapter for displaying server validation errors
1 parent aa8115a commit e100b17

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,3 +168,52 @@ application adapter to your Ember app and override the buildURL method::
168168
}
169169
});
170170

171+
Displaying Server Side Validation Messages
172+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
173+
174+
Ember Data does not ship with a default implementation of a validation error
175+
handler except in the Rails ActiveModelAdapter so to display validation errors
176+
you will need to add a small client adapter::
177+
178+
App.ApplicationAdapter = DS.RESTAdapter.extend({
179+
ajaxError: function(jqXHR) {
180+
var error = this._super(jqXHR);
181+
if (jqXHR && jqXHR.status === 400) {
182+
var response = Ember.$.parseJSON(jqXHR.responseText),
183+
errors = {},
184+
keys = Ember.keys(response);
185+
if (keys.length === 1) {
186+
var jsonErrors = response[keys[0]];
187+
Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors), function(key) {
188+
errors[key] = jsonErrors[key];
189+
});
190+
}
191+
return new DS.InvalidError(errors);
192+
} else {
193+
return error;
194+
}
195+
}
196+
});
197+
198+
The adapter above will handle the following response format when the response has
199+
a 400 status code. The root key ("post" in this example) is discarded::
200+
201+
{
202+
"post": {
203+
"slug": ["Post with this Slug already exists."]
204+
}
205+
}
206+
207+
To display all errors add the following to the template::
208+
209+
{{#each message in errors.messages}}
210+
{{message}}
211+
{{/each}}
212+
213+
To display a specific error inline use the following::
214+
215+
{{#each errors.title}}
216+
<div class="error">{{message}}</div>
217+
{{/each}}
218+
{{input name="title" value=title}}
219+

0 commit comments

Comments
 (0)