如何为复选框实现 vuelidate 的 requiredUnless 验证器

How to implement requiredUnless validator of vuelidate for checkboxes

使用 Vuelidate,因为 'required' 验证器现在认为布尔值 'false' 是一个有效值,您必须像 sameAs: sameAs( () => true ) 一样使用 'sameAs' 来实现复选框所需的验证。如何使用 vuelidate 实现复选框的 'requiredUnless' 验证,其中仅当 属性 不是特定值时才需要选中复选框?

我找不到使用 vuelidate 进行验证的方法。所以我制作了一种方法,它通过执行一个方法来切换 css class 并将 $v 对象传递给它,并且只有 运行 在值不是选定值时进行验证。

 <div class="input inline" :class="{invalid: checkCountry($v)}">

验证者

 Validations: {
  terms: {
    sameAs: sameAs(vm => {
      if (!(vm.country === 'germany')) {
        return true;
      } else {
        return false;
      }
    })

方法

methods: {
    checkCountry($v) {
      if (this.country === 'germany') {
        return false;
      } else {
        return $v.terms.$invalid;
      }
    }

false 被验证为有效,因此您需要将其更改为空字符串,我会在 watch 中执行此操作:

    data() {
        return {
            email: '',
            age: null,
            password: '',
            confirmPassword: '',
            country: 'Malta', 
            hobbyInputs: [],
            terms: '',
            countries,                
        }
    },        
    validations: {
      terms: {
        required: requiredUnless(vm => {
          return vm.country === 'Malta'
        }),
      }
    },
    watch: {
      terms() {
        if (!this.terms) {
          this.terms = '';
        }
      }
    },