我遇到了在HTML中呈现错误的问题。
视图模型:
import {autoinject} from 'aurelia-framework';
import { ValidationRules, ValidationController, ValidationControllerFactory } from 'aurelia-validation';
// Models
import { NewCustomer } from '../../models/customer';
@autoinject
export class Register {
controller: ValidationController;
customer: NewCustomer;
constructor(controllerFactory: ValidationControllerFactory, customer: NewCustomer) {
this.controller = controllerFactory.createForCurrentScope();
this.customer = customer;
this.controller.addObject(this.customer);
}
validate(): void {
this.controller.validate().then(res => {
console.log(res);
if(res.valid) {
this.register();
}
});
}
}
ValidationRules
.ensure((c: NewCustomer) => c.first_name).displayName('first name').required().withMessage(`\${$displayName} cannot be blank.`)
.ensure((c: NewCustomer) => c.last_name).displayName('last name').required().withMessage(`\${$displayName} cannot be blank.`)
.ensure((c: NewCustomer) => c.email).displayName('first name').email().required().withMessage(`\${$displayName} cannot be blank.`)
.ensure((c: NewCustomer) => c.phone_number).displayName('phone number').matches(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/).withMessageKey('invalid phone number').required().withMessage(`\${$displayName} cannot be blank.`)
.ensure((c: NewCustomer) => c.password).displayName('password').minLength(7).required().withMessage(`\${$displayName} cannot be blank.`)
.on(NewCustomer);
和示例输入:
<div class="sb-input-group no-margin" validation-errors.bind="first_nameErrors">
<label>First Name</label>
<input value.bind="customer.first_name" placeholder="First Name" class="sb-input-control">
<span class="help-block danger" repeat.for="errorInfo of first_nameErrors">
${errorInfo.error.message}
<span>
</div>
现在每当我提交表单并检查控制台时,我都会看到验证规则正在被正确选取;但它们不在视图中渲染。我也尝试过做validation-errors.bind="customer.first_nameErrors"
而且也没用。将错误绑定到视图的正确格式是什么?
编辑:这是NewCustomer对象
export class NewCustomer {
first_name: string;
last_name: string;
email: string;
phone_number: string;
password: string;
companies: Company[];
selected_company_id: string;
}
答案 0 :(得分:2)
看起来你错过了html中的“&amp; validate”标记来向你的验证控制器注册绑定实例。
同时检查验证渲染器(周围有一些Bootstrap Validation Renderers)可以避免在任何地方添加错误范围。
大部分内容都在the docs,但我需要多次通过才能理解这一切!