Search code examples
javascriptvalidationember.jsember-cp-validations

Getting 'TypeError: user is null' when trying to validate form using ember-cp-validations


I am attempting to add form validation using ember-cp-validations and am following the basic steps in their video TypeError: user is null in the console. I am very new to ember and I am sure its something very basic I am overlooking.

register-form component

import Ember from 'ember';

export default Ember.Component.extend({
  user: null,

  actions: {
    save() {

      let user = this.get('user');

      user.validate()
        .then(({ validations }) => {

          if (validations.get('isValid')) {
            user.save();
          } else {
            alert("not valid");
          }

        });
    }
  }
});

user model

import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
  firstname: validator('presence', true),

  email: [
    validator('presence', true),
    validator('format', { type: 'email' })
  ],

  username: validator('presence', true),

  password: [
    validator('presence', true),
    validator('length', {
      min: 4
    })
  ]
});

export default DS.Model.extend(Validations, {
  firstname:  DS.attr('string'),
  email:      DS.attr('string'),
  username:   DS.attr('stirng'),
  password:   DS.attr('string')
});

Solution

  • You need to pass new user to the component like this :

    //routes/users/new.js
    ...
    model(){
      return this.get('store').createRecord('user');
    }
    ...
    

    And in the template you put the register component do like :

    //templates/users/new.hbs
    {{register-form user=model}}