Skip to content

Instantly share code, notes, and snippets.

@hellosteadman
Created March 9, 2018 14:26
Show Gist options
  • Save hellosteadman/eedca3d67d03baffecdb9130d6edd385 to your computer and use it in GitHub Desktop.
Save hellosteadman/eedca3d67d03baffecdb9130d6edd385 to your computer and use it in GitHub Desktop.
Adding server-side validation support to ember-bootstrap-cp-validations

I spent a day trying to figure out how to get ember-bootstrap to handle server-side (HTTP 422) validation errors. I tried the three supported validation packages (two of which don't work with the newest version of Ember.js), and finally began to understand that ember-cp-validations has nothing to do with server-side errors.

So, taking inspiration from ember-bootstrap-ds-error-validations, which causes errors when combined with another validation package, I was able to put something fairly simple in place.

I'll be honest, I don't entirely know what the app/components/bs-form.js file is doing (this was taken from ember-bootstrap-cp-validations I think), but that, combined with app/components/bs-form/element.js, which takes the server-side messages and places them in the customError property (as a computed property), I get a combination of client- and server-side validation that works. At least for me.

// Replace underscores in filename with slashes
import BsForm from 'ember-bootstrap-cp-validations/components/bs-form';
import ObjectProxy from '@ember/object/proxy';
import { Promise } from 'rsvp';
import { computed } from '@ember/object';
export default BsForm.extend(
{
hasValidator: computed.notEmpty('model.validate'),
validate(model) {
return new Promise(
(resolve, reject) => {
let m = model
if(model instanceof ObjectProxy) {
m = model.get('content')
}
m.validate().then(
() => model.get(
'validations.isTruelyValid'
) ? resolve() : reject(),
reject
)
}
)
}
}
)
// Replace underscores in filename with slashes
import BsFormElement from 'ember-bootstrap-cp-validations/components/bs-form/element';
import { computed } from '@ember/object';
import { defineProperty } from '@ember/object';
export default BsFormElement.extend(
{
setupValidations() {
this._super(...arguments)
defineProperty(
this,
'customError',
computed.readOnly(`model.errors.${this.get('property')}.0.message`)
)
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment