Yup嵌套架构验证 [英] Yup nested schema validation

查看:233
本文介绍了Yup嵌套架构验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据用户选择的选择选项"有条件地验证对象,问题是我正在渲染货币列表,并且很难将其设置为必填字段,因为我必须通过在一个空对象开始.

I'm trying to validate an object conditionally on a Select Option that's been chosen by a user, the issue is I'm rendering a currency list and having immense difficulty trying to make it a required field, as I have to pass in an empty object to start with.

我的代码栈是React,Formik和Yup(所有最新版本).

My code stack is React, Formik and Yup (all recent versions).

对象架构

category: 'A',
details: {
   name: '',
   price: 0,
   stock: 0,
   currency: {
      label: '',
      code: '',
      symbol: '',
      alpha_2: '',
    }
}

Yup模式

category: Yup.string().required('You must pick a category'),
details: Yup.object().when('category', {
  is: 'A',
  then: Yup.object({
       label: Yup.string().required(`Select the currency you're retailing in`),
        code: Yup.string().required(`Select the currency you're retailing in`),
        symbol: Yup.string().required(`Select the currency you're retailing in`),
        alpha_2: Yup.string().required(`Select the currency you're retailing in`),
    }),
})

使用上述代码,表单通过了验证,货币对象具有空值''的列表,这是不希望的结果.

With the above code the form is passing validation and the currency object has a list of empty values '', which is an undesired outcome.

您如何进行模式触发器验证?

How do you make the schema trigger validation?

推荐答案

您未针对存储label/code/symbol/alpha_2details.currency进行验证. 在schema.details中,then应该由一个Yup.object组成,该Yup.objectcurrency属性中存储了另一个Yup.object,然后定义要用于label/code/symbol/alpha_2的验证.

You are not validating against details.currency where label/code/symbol/alpha_2 are stored. In the schema.details, then should be composed of a Yup.object which has another Yup.object stored in currency property and then define the validations you want for label/code/symbol/alpha_2.

示例:

const yup = require("yup");

const schema = yup.object({
    category: yup.string().required('You must pick a category'),
    details: yup.object().when('category', {
        is: 'A',
        then: yup.object({
            currency: yup.object({
                label: yup.string().required(`[1] Select the currency you're retailing in`),
                code: yup.string().required(`[2] Select the currency you're retailing in`),
                symbol: yup.string().required(`[3] Select the currency you're retailing in`),
                alpha_2: yup.string().required(`[4] Select the currency you're retailing in`),
            })
        }),
    })
})

let state = {
    category: 'A',
    details: {
        name: '',
        price: 0,
        stock: 0,
        currency: {
            label: 'a',
            code: 'b',
            symbol: 'c',
            alpha_2: 'd',
        }
    }
}

schema.validate(state).then(console.log).catch(err => console.log(err))

这篇关于Yup嵌套架构验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆