获取' TypeError:user为null'尝试使用ember-cp-validations验证表单时

时间:2017-02-19 18:37:02

标签: javascript validation ember.js ember-cp-validations

我正在尝试使用ember-cp-validations添加表单验证,并遵循控制台中video TypeError: user is null的基本步骤。我很贪婪,我确信这是我非常基本的东西。

注册表单组件

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");
          }

        });
    }
  }
});

用户模型

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')
});

1 个答案:

答案 0 :(得分:1)

您需要将新用户传递给组件,如下所示:

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

在模板中,您将注册组件放在:

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