Aurelia验证嵌套对象 [英] Aurelia validating nested objects
问题描述
我正在尝试验证Aurelia ViewModel的对象属性.
I'm trying to validate an object property of an Aurelia ViewModel.
@autoinject
class AddUserForm {
user: User;
controller: ValidationController;
constructor(controllerFactory: ValidationControllerFactory) {
this.controller = controllerFactory.createForCurrentScope();
}
validate() {
this.controller.validate.then(res => {
console.log(res.valid);
})
}
}
ValidationRules
.ensure((u: User) => u.id).displayName('User').required()
.on(AddUserForm)
ViewModel->视图
<template>
<form click.trigger="validate()">
<input type="text" value.bind="user.id & validate" />
</form>
</template>
用户
class User {
id: string
}
我遇到的问题是验证器没有拾取嵌套的用户对象.我缺少某些东西可以使它正常工作吗?我阅读了 docs 和似乎这应该工作.我正在使用插件的^1.0.0
版本.
The issue I'm having is that the validator is not picking up the nested user object. I'm I missing something to get this working? I read the docs and it seems like this should work. I'm using version ^1.0.0
of the plugin.
推荐答案
问题出在您的ValidationRules中:
The problem is in your ValidationRules:
ValidationRules
.ensure((u: User) => u.id).displayName('User').required()
.on(AddUserForm)
需要成为
ValidationRules
.ensure((u: User) => u.id).displayName('User').required()
.on(User)
然后要使控制器运行此规则,您要么需要在值中包括& validate".对该属性绑定 ,如下所示:
Then to get the controller to run this rule you either need to include "& validate" somewhere in your value.bind for that property, like this:
<input value.bind="user.id & validate" />
或在调用controller.validate()之前,将整个对象添加到控制器中,如下所示:
or before you call controller.validate(), add the entire object to the controller like this:
this.controller.addObject(this.user);
我一直都使用.addObject ,因为它会使验证在未包含在标记中的属性上运行,而我发现我更喜欢这样做.
I use .addObject all the time because it causes validation to run on properties that aren't included in your markup, and I find I prefer that.
这篇关于Aurelia验证嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!