0

在 vuelidate 中添加可选验证对象的正确方法是什么?

给定一个验证形状:

validations: {
    vehicles: {
        $each: {
            type: {
                required
            },
            engine: {
                required: requiredIf((vehicle) => vehicle.type == 'car'),

                size: {
                    required
                },

                power: {
                    required
                }
            }
        }
    }
}

我的期望是,对于这种类型的车辆,bike我不需要提供尺寸和功率,因为engine​​不需要它们的父级。但是验证返回无效。

4

2 回答 2

3

您可以做的不是要求引擎的每个子字段都需要,而是要求每个引擎同时具有sizepower,以便每次有引擎时它都必须具有这些键。将此与 requiredIf 一起添加,您将获得以下内容:Every vehicle must have a type, if it is a car then an engine is required and every engine must have a power and size.

以下代码段显示了它的工作原理。

Vue.use(vuelidate.default);
let { required, requiredIf, helpers } = validators;
const contains = (param) =>
  (value) => !helpers.req(value) ||
    param.reduce((accum, curr) => accum && curr in value, true);
var app = new Vue({
  el: '#app',
  data: () => ({
    vehicles: [
      {
        type: 'car',
        engine: {
          size: 5,
          power: 2.5,
        }
      },
      {
        type: 'bike',
      }
    ]
  }),
  validations: {
    vehicles: {
      $each: {
        type: { required },
        engine: {
          required: requiredIf((value) => value.type === 'car'),
          contains: contains(['size', 'power']),
        }
      }
    }
  },
  created() {
    console.log(this.$v.$invalid);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.5/dist/vuelidate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.5/dist/validators.min.js"></script>
<div id="app"></div>

于 2020-02-17T21:24:06.883 回答
1

I went through a similar situation recently and resolved using 'parentVm', as documented at https://vuelidate.js.org/#sub-accessing-component.

You should try this:

...

engine: {
  required: requiredIf((parentVm) => {return parentVm.type === 'car'}),
  size: {between: between(yourMinValue, yourMaxValue)},
  power: {between: between(yourMinValue, yourMaxValue)},
} 
...
于 2020-05-25T01:36:40.640 回答