繁体   English   中英

Yup 模式中的可选字段验证

[英]Optional field validation in Yup schema

我正在使用带有yupreact-hook-form进行表单验证,并希望某些字段是可选的(null)。

根据他们的文档,我正在使用nullable()optional()但它仍在得到验证:

export const updateAddressSchema = yup.object({
  address: yup
    .string()
    .nullable()
    .optional()
    .min(5, "Address must be more than 5 characters long")
    .max(255, "Address must be less than 255 characters long"),
  city: yup
    .string()
    .nullable()
    .optional()
    .max(32, "City name must be less than 32 characters long"),
  postal_code: yup
    .string()
    .nullable()
    .optional()
    .length(10, "Postal code must be 10 characters long"),
  phone: yup
    .string()
    .nullable()
    .optional()
    .min(10, "Phone number must be more than 10 characters long")
    .max(20, "Phone number must be less than 20 characters long"),
});

有什么正确的方法可以做到这一点吗?

您需要使用.when进行条件验证,如下所示。 我只添加了addresscity ,你可以像这样添加其他的。

export const updateAddressSchema = yup.object().shape({

  address: yup.string().when("address", (val, schema) => {
     if (val) {  
        if(val.length > 0) {  //if address exist then apply min max else not
          return yup.string().min(5, "min 5").max(255, "max 255").required("Required");
       } else { 
          return yup.string().notRequired();
       }

     } else {
          return yup.string().notRequired();
     }
  }),

  city: yup.string().when("city", (val, schema) => {
     if (val) {
        if(val.length > 0) {
          return yup.string().max(32, "max 32").required("Required");
       }
       else { 
          return yup.string().notRequired();
       }
     } else {
          return yup.string().notRequired();
     }
  }),
  
 }, [
     ["address", "address"], 
     ["city", "city"], 
    ]                   //cyclic dependency
 );

此外,您需要添加循环依赖

非常感谢@Usama 的回答和解决方案!

我在使用他们的解决方案时遇到了另一个问题。 如果提交了空值,我的后端 API 会忽略空值并返回前一个值。 问题在于,在初始渲染时,文本字段的值为 null,但在选择并键入然后删除键入的字母以使其再次为空(不提交)后,其值将变为空字符串,因此我的 API 会抛出错误并且不会更新用户信息。

我设法修复它的方法是使用yup.transform()方法将类型从空字符串转换为 null 如果未填充文本字段:

export const updateAddressSchema = yup.object().shape(
  {
    address: yup.string().when("address", (value) => {
      if (value) {
        return yup
          .string()
          .min(5, "Address must be more than 5 characters long")
          .max(255, "Address must be less than 255 characters long");
      } else {
        return yup
          .string()
          .transform((value, originalValue) => {
            // Convert empty values to null
            if (!value) {
              return null;
            }
            return originalValue;
          })
          .nullable()
          .optional();
      }
    }),
    ......................
  },
  [
    ["address", "address"],
    ......................,
  ]
);

我真的希望这对某人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM