我在获取要在 HTML 中呈现的错误时遇到问题。
View 模型:
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>
现在,每当我提交表单并检查控制台时,我都会看到验证规则被正确拾取;但是它们没有在 View 中呈现。我也试过 validation-errors.bind="customer.first_nameErrors"
但也没有用。将错误绑定(bind)到 View 的正确格式是什么?
编辑:这是 NewCustomer 对象
export class NewCustomer {
first_name: string;
last_name: string;
email: string;
phone_number: string;
password: string;
companies: Company[];
selected_company_id: string;
}
最佳答案
看起来您在 html 中缺少“& validate”标记来向您的验证 Controller 注册绑定(bind)实例。
同时检查一个验证渲染器(周围有一些 Bootstrap Validation Renderers),它可以避免在任何地方添加错误跨度。
大部分在 the docs 中,但我花了很多时间才理解这一切!
关于javascript - Aurelia 显示每个输入的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43641279/