如何浓缩“何时”验证

时间:2018-11-19 23:30:26

标签: javascript validation yup

如果单个条件为真,我有几个必填字段。是否有更好的方法来压缩此代码,以避免对所有这些字段重复使用when

const requiredForDiffAddress = {
    is: false,
    then: Yup.string().required()
};

export const BillingAddressYupValidationSchemaShape = {
  useShippingAddress: Yup.boolean().default(true).required(),
  street: Yup.string()
      .when('useShippingAddress', requiredForDiffAddress),
  city: Yup.string()
      .when('useShippingAddress', requiredForDiffAddress),
  state: Yup.string()
      .when('useShippingAddress', requiredForDiffAddress),
  zipCode: Yup.string()
      .when('useShippingAddress', requiredForDiffAddress),
};

或者获取更现实,更复杂的示例

const buildRequiredForDiffAddress = requiredText => ({
    is: false,
    then: Yup.string().required(requiredText)
});

export const BillingAddressYupValidationSchemaShape = {
  useShippingAddress: Yup.boolean().default(true).required(),
  street1: Yup.string().when('useShippingAddress', 
      buildRequiredForDiffAddress("How will we know where to send your order?")),
  city: Yup.string().when('useShippingAddress', 
    buildRequiredForDiffAddress("What city do you live in?")),
  state: Yup.string().when('useShippingAddress',
    buildRequiredForDiffAddress("State please!")),
  zipCode: Yup.string().when('useShippingAddress', 
      buildRequiredForDiffAddress("Zip Code please!")),
};

1 个答案:

答案 0 :(得分:0)

TL; DR:问题中发布的解决方案可能是处理仅当满足条件的情况下才基于某些其他字段的值的必填字段的最佳方法*

扩展答案

JsonSerializerSettings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full之后,我已经看了很多。

他建议

  

扩展与requiredIf方法混合以封装这种东西

我研究了使用lazy形式会涉及到什么。扩展路由似乎比懒惰路由要好,但是最后,我觉得我拥有的可能是最好的解决方案。

我创建了这个相当详细的CodeSandbox,是有人想刺中一个更好的解决方案。我会很乐意为此更改接受的答案。

messaging the creator of Yup

* ...,并且您希望每个字段自定义错误消息。似乎您可以使用默认消息传递,但是发布的示例可能不是最简单的解决方案。