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

时间:2018-03-02 15:45:19

标签: validation properties aurelia message aurelia-validation

我有一个自定义文本字段组件,它封装了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>

1 个答案:

答案 0 :(得分: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 });
        }
      }
    }
    
  5. 这会为您提供自定义元素中的错误。你也可以直接在那里进行渲染。

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

相关问题