Cohars
Cohars

Reputation: 4022

Ember form validation

I'm kind of new to Ember and I'm on something that should be quite simple. Just trying to validate a form actually. Using ember-forms and ember-validations.

Here is the part of the structure, I'll be quite exhaustive so you can get to the point but there is really not a lot of code:

 /app
   /controllers
     /admin
       /create-user.js
   /models
     /admin
       /create-user.js
   /routes
     /admin
       /create-user.js
   /templates
     /admin
       /create-user.js

First, I'm not sure it's the good structure, especially about the model.

The model:

import DS from 'ember-data';
import EmberValidations from 'ember-validations';

export default DS.Model.extend(EmberValidations, {
  entity: DS.attr()
}).reopen({
  validations: {
    entity: {
     presence: true,
     length: { minimum: 5 }
    }
  }
});

The controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    createUser() {
      console.log("create");
    }
  }
});

The route:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.createRecord('admin/create-user');
  }
});

The template:

<h3>Create User</h3>

<div class="row">
  <div class="col-sm-6">
    {{#em-form action="createUser" model=admin/create-user}}
      {{em-input
        label="Name / Entity"
        property="entity"
        placeholder="The name of the user or the entity"}}

    {{/em-form}}
  </div>
</div>

I know I'm missing something and I'm pretty sure it has to do with the model (I tried a lot of thing such as model=admin/create-user in the template).

EDIT: there's no error or whatever in the console, the validation is just not called.

Thx for your help!

Upvotes: 0

Views: 301

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245429

The first thing that jumps out at me is the fact that you never, anywhere in your code, check to see if the data is valid via:

// Somewhere in your controller
this.get('isValid');

The second is that you're validations are defined on the controller rather than the model. That works great if your controller extends ObjectController (which is now deprecated) which proxies properties automatically to the model.

If you're extending Controller and you want to validate the model, you need to define them a bit differently:

validations: {
  'model.entity': {
    presence: true,
    length: { minimum: 5 }
  }
}

The third is that you're never actually passing an instance of your model to the controller via the route (even though validations should still work):

export default Ember.Route.extend({
  model: function() {
    // assuming you're using Ember Data
    // find the model with id of 1
    return this.store.find('admin/create-user', 1);
  }
});

Upvotes: 1

Related Questions