【问题标题】:How do I create a custom Vee-Validate rule in TypeScript?如何在 TypeScript 中创建自定义 Vee-Validate 规则?
【发布时间】:2020-12-12 21:46:00
【问题描述】:

我正在尝试为我用 TypeScript 编写的 VueJS 组件创建自定义 VeeValidate 规则。该规则需要按照VeeValidate - Cross Field Validation 的指南一起验证两个字段 - 这是一个 sn-p:

            <div class="form-group">
                <checkbox name="noBarcode" v-model="currentProduct.noBarcode" label=" " />
                <i class="info-icon btn-base-element-icon fa fa-info-circle" data-toggle="tooltip" data-placement="left" title="" data-original-title="Tick this checkbox if this product does not have a barcode."></i>
            </div>
            <div class="form-group">
              <text-input v-model="currentProdcut.barcode" label="BarCode" name="barcode" rules="barcode:@noBarcode" />
            </div>

text-inputcheckbox 都是自定义表单组件,它们按照 Advanced Input Fields 合并了 ValidationProvider

我的自定义规则目前如下所示:


extend('barcode', {
  params: ['checkbox'],
  validate(value, { checkbox }) {
    return checkbox === true || value.length > 0
  },
  message: "Please enter a barcode. If this product does not have a barcode, tick the checkbox above."
})

问题是目前 TypeScript 正在解释这一点,Vetur 抛出以下错误消息(正确):

类型'any[] 上不存在属性'checkbox' |记录'.

我还没有找到任何在 TypeScript 中编写自定义规则的示例,所以在那里寻找指针......

【问题讨论】:

    标签: typescript vue.js vee-validate


    【解决方案1】:

    不确定这是否合法,但帮助我摆脱错误消息的是向第二个参数添加一个接口。像这样的

    interface ParamI {
     [index: string]: any
    }
    

    然后在您的验证函数中

    validate(value, { checkbox }: ParamI) {
        return checkbox === true || value.length > 0
      },
    

    【讨论】:

    • 到目前为止,我已经解决了这个问题:{ checkbox }: Record&lt;string, unknown&gt;,但尚未对其进行测试。看看情况如何:)