Aurelia验证 - 访问特定属性的验证错误的最佳方法是什么?

问题描述 投票:0回答:1

我有一个自定义的文本字段组件,它封装了mdl文本字段。我通过其可绑定属性传递所需的值。我想在通用视图模型中声明(并验证)验证规则,然后将可能的验证错误传递给每个文本字段(它应该显示它想要的)。

我目前的伪代码:

<template>
    <text-field 
        value.two-way="entity.value1">
    </text-field>
    <text-field 
        value.two-way="entity.value2">
    </text-field>
</template>

如何将value1的验证错误传递给第一个文本字段,将value2的验证错误传递给第二个?

我能做的最好的是:

<template>
    <div validation-errors.bind="firstValidationErrors">
        <text-field 
            value.two-way="entity.value1"
            errors.bind="firstValidationErrors">
        </text-field>
    <div>
    <div validation-errors.bind="secondValidationErrors">
        <text-field 
            value.two-way="entity.value2"
            errors.bind="secondValidationErrors">
        </text-field>
    <div>
</template>

但是我必须在viewmodel中创建每个验证错误数组(我不确定我是否真的必须但是linting强迫我)。而且我必须在页面中包装每个控件。有没有更好的办法?

我可以这样做吗?

<template>
    <text-field 
        value.two-way="entity.value1"
        validation-errors.bind="firstValidationErrors"
        errors.bind="firstValidationErrors">
    </text-field>

    <text-field 
        value.two-way="entity.value2"
        validation-errors.bind="secondValidationErrors"
        errors.bind="secondValidationErrors">
    </text-field>
</template>
validation properties aurelia message aurelia-validation
1个回答
2
投票

既然你希望你的text-field完全控制显示错误,为什么不把它变成validation renderer呢?

这很简单:

  1. 通过构造函数将ValidationControllerElement注入自定义元素
  2. bind()你注册它:this.controller.addRenderer(this);
  3. unbind()上,您可以像这样取消注册:this.controller.removeRenderer(this);
  4. 像这样实现render方法: public render(instruction: RenderInstruction) { for (const { result } of instruction.unrender) { const index = this.errors.findIndex(x => x.error === result); if (index !== -1) { this.errors.splice(index, 1); } } for (const { result, elements } of instruction.render) { if (result.valid) { continue; } const targets = elements.filter(e => this.element.contains(e)); if (targets.length) { this.errors.push({ error: result, targets }); } } }

这会给你自定义元素中的错误。你也可以直接在那里进行渲染。

请注意,我给你的这个例子几乎是来自validation-errors自定义属性的复制粘贴source

© www.soinside.com 2019 - 2024. All rights reserved.