我遇到了在HTML中渲染错误的问题。
ViewModel:
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;
}
看起来您缺少html中的"&amp; validate"标记在验证控制器中注册绑定实例。
还请查看验证渲染器(周围有一些引导程序验证器(,可以使您免于添加错误跨越到处。
大部分是在文档中,但是我花了很多通行来理解这一切!