簡體   English   中英

Aurelia驗證-訪問特定屬性上的驗證錯誤的最佳方法是什么?

[英]Aurelia Validation - What is the best way to access validation error on specific property?

我有一個自定義的文本字段組件,該組件封裝了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中創建每個驗證錯誤數組(我不確定是否確實必須這樣做,但是可以強制我這樣做)。 而且我還必須將每個控件包裝在頁面中。 有沒有更好的辦法?

我可以做這樣的事情嗎?

<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>

由於您希望您的text-field完全控制顯示錯誤,因此為什么不將其變成驗證渲染器呢?

這很簡單:

  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定制屬性的復制粘貼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM