这个问题是关于特定的插件 - ember-cli-simple-validation。
让我们假设有两个模型
User = DS.Model.extend({
name: DS.attr()
emails: DS.hasMany('email')
})
Email = DS.Model.extend({
address: DS.attr()
emails: DS.belongsTo('user')
})
和用户动态创建电子邮件:
<button {{action 'createEmail'}}>Add Email</button>
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{/each}}
是否可以在这种情况下使用ember-simple-validaiton来验证每封电子邮件上是否存在地址?
我尝试使用validateEach
,但在https://github.com/toranb/ember-cli-simple-validation/blob/master/addon/mixins/validate.js#L66
Error while processing route: profile self.get(...).forEach is not a function TypeError: self.get(...).forEach is not a function
错误
控制器:
import Ember from 'ember';
import {ValidationMixin, validateEach} from "ember-cli-simple-validation/mixins/validate";
var isLegit = function(address) {
return address && address.length > 3;
};
export default Ember.Controller.extend(ValidationMixin, {
emailAddressValidation: validateEach("model.emails", isLegit),
actions: {
createChildren: function(type) {
this.store.createRecord(type, {profile: this.get('model')});
},
});
模板:
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{#validation-error-field submitted=submitted field="address" model=mode.emails index=index validation="basic"}}invalid address{{/validation-error-field}}
{{/each}}
模型:
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Model.extend{
address: DS.attr(''),
kind: DS.attr(''),
contactable: DS.belongsTo('contactable', { polymorphic: true, inverse: 'emails', async: false }),
kindIsPrimed: false,
kindChanged: Ember.observer('kind', function () {
this.set('kindIsPrimed', true);
}),
addressIsPrimed: false,
addressChanged: Ember.observer('address', function () {
this.set('addressIsPrimed', true);
})
});
答案 0 :(得分:0)
表面上(不运行代码)你可能会改变你的hbs
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{#validation-error-field submitted=submitted field="address" model=mode.emails index=index validation="basic"}}invalid address{{/validation-error-field}}
{{/each}}
改为......
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{#validation-error-field submitted=submitted field="address" model=email index=index validation="basic"}}invalid address{{/validation-error-field}}
{{/each}}
在validateEach场景中(对于数组验证),您需要在每次迭代时设置模型和索引。模型应该仍然是单个模型(而不是数组本身)。
另一个在插件中测试的示例
https://github.com/toranb/ember-cli-simple-validation/blob/master/tests/dummy/app/templates/many.hbs