Skip to content

Instantly share code, notes, and snippets.

@toranb
Last active August 29, 2015 14:15
Show Gist options
  • Save toranb/9fbe70c7254e0699de60 to your computer and use it in GitHub Desktop.
Save toranb/9fbe70c7254e0699de60 to your computer and use it in GitHub Desktop.
model backed form validation for ember.js in 3 easy steps
// model backed form validation for ember.js using the ember-cli-simple-validation addon
// jsbin to demo the user experience http://emberjs.jsbin.com/fovolu/2/
// 1) add the input and validation-error-field component to your template
{{input value=model.name placeholder="name"}}
{{#validation-error-field field="name" submitted=submitted model=model validation=nameValidation}}invalid name{{/validation-error-field}}
<button {{action "save"}}>Save</button>
// 2) add the mixin to your controller and setup the validation rules (optional 2nd argument supports regex/function)
import Ember from "ember";
import { ValidationMixin, validate } from "ember-cli-simple-validation/mixins/validate";
export default Ember.Controller.extend(ValidationMixin, {
nameValidation: validate("model.name", /^\w{5}[^$%@!]+$/),
actions: {
save: function() {
this.set("submitted", true);
if(this.get("valid")) {
this.transitionToRoute("success");
}
}
}
});
// 3) define the model and each property you want to validate
import { attr, Model } from "ember-cli-simple-store/model";
export default Model.extend({
name: attr()
});
// to see a more full featured application checkout this example on github
https://github.com/toranb/ember-cli-store-dirty-tracking-example
// if you want to see just how simple the validation library is checkout the source on github
https://github.com/toranb/ember-cli-simple-validation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment