我有一个值的输入字段,该值应该正好有 5 位数字。我想在立即输入数字以外的字符(onChange)时显示错误,但仅在模糊时显示字符串长度不足的错误。
我的规则目前看起来是这样的:
ValidationRules
.ensure("myInput")
.matches(new RegExp(/[0-9]/))
.minLength(5)
.on(this);
MaxLength是通过在html中设置maxlength来限制的。
如果我将验证触发器设置为“onChange”以立即响应错误字符,我还会收到一条错误消息,表明在输入正确的数字时不满足 minLength 规则,直到输入了 5 个数字为止。
我想要的行为是应用 matches-rule onChange 和 minLength-rule onBlur。
是否有可能在不同事件的同一属性上应用两个规则?我知道如何手动验证,但不知道如何区分规则。
最佳答案
您可以使用 when
流畅 API 来满足您的需求。像这样的东西 -
ValidationRules
.ensure('email')
.email()
.required()
.when((order) => {
if (order.length > 4) {
order._ruleHasBeenMet = true;
}
return order.length > 4 && order._ruleHasBeenMet;
}
.withMessage('Email is required when shipment notifications have been requested.');
关于Aurelia验证: applying some rule on change and some on blur on same property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41137697/