【问题标题】:How to use aurelia-validation to array item如何使用 aurelia-validation 来排列项目
【发布时间】:2017-05-22 04:29:38
【问题描述】:

请帮助我ensureForEach,我找不到那个点的文件。我有一堂课:

export class EnterReplacements {
    replacements: Replacement[] = null;

    constructor(
        private router: Router,
        private eventAggregator: EventAggregator,
        private repoCreator: RepoCreator,
        protected validation: Validation
    ) {
        this.validation = validation.on(this)
            .ensureForEach('replacements')
            .ensure('value')
            .isNotEmpty()
            .etc(); // repeat all the same stuff as in the Item validation
    }
}

运行时出错:

ERROR [app-router] Error: Error instantiating EnterReplacements. Check the inner error for details.

这是我的html:

<div class="col-xs-12 col-sm-6 col-lg-4" repeat.for="replacement of replacements">
    <input  class="string-input" type="text" value.bind="replacement.value" placeholder.bind="replacement.friendlyName" change.delegate="$parent.onChanged()"/>
</div>

我需要验证 replacements 数组中项目的所有 value 属性不为空。请帮忙!!!

【问题讨论】:

  • 只是我们的好奇心。你从哪里得到 .ensureForEach ?我只能在讨论可能实现的票证中找到参考。但就我所见,它还没有。 github.com/aurelia/validation/issues/10
  • 没错,没有 ensureForEach
  • 我们还有其他方法来验证数组中的项目吗?

标签: validation typescript aurelia


【解决方案1】:

根据Aurelia-Validation 的最新版本,Rules 用于验证数组是否已填充可以通过两种方式完成:

最简单的方法是使用minItems(count),例如我们将使用minItems(1) 来确保数组中至少填充了一项。

第二种方式也有效(我们可以将其用于非常具体的验证规则)

satisfies(value => Array.isArray(value) && value.length > 0)

【讨论】:

    【解决方案2】:

    您可以使用通用函数进行验证并自己进行(这将在顶层显示为数组的验证)

    this.validation = validation.on(this)
            .ensure('replacements')
            .isNotEmpty()
            .passes(replacementsArray => {
               let valid = true;
               replacementsArray.forEach(v => {
                 valid = v != null && valid;
               });
               return valid;
             });
    

    注意事项:
    - isNotEmpty() 将首先运行(无论它出现在哪里)
    - 我相信 isNotEmpty 是让.passes() 运行所必需的(这是我的经验,虽然我在文档中没有看到提及)
    - 我实际上不知道你想为每个值验证什么,所以我做了一个空等价检查,我认为这会满足你 isNotEmpty 的意图?你可能想要改变它。

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2023-04-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 2018-03-11
      • 2017-10-30
      相关资源
      最近更新 更多