You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Yup为数组对象的weight属性设置验证:实现单个值范围校验及总和小于100的校验

Solution for Yup Array Weight Sum Validation

Hey there! You're already halfway there with your Yup validation setup—nice work on the individual weight range checks. To add the total sum validation for all weight values in the array, we can use Yup's test() method, which lets us define custom validation logic that isn't covered by the built-in methods.

Here's the updated code that includes both your existing rules and the total sum check:

const ParamValidator = Yup.object()
  .shape({
    params: Yup.array()
      .of(
        Yup.object()
          .shape({
            name: Yup.string.max(30).required(),
            weight: Yup.number().min(0).max(100).required(),
          })
          .required(),
      )
      .required()
      // Custom test to validate total weight sum
      .test(
        'total-weight-limit',
        'The sum of all weights must be less than 100',
        (params) => {
          // Calculate total weight by reducing the array
          const totalWeight = params.reduce((sum, item) => sum + item.weight, 0);
          // Return true if validation passes, false if it fails
          return totalWeight < 100;
        }
      ),
  });

Let's break down the custom test logic:

  • We chain .test() directly onto the Yup.array() definition for params.
  • The first argument is a unique identifier for the test (total-weight-limit)—this helps with debugging and targeting specific errors.
  • The second argument is the user-friendly error message that shows up when the sum exceeds the limit.
  • The third argument is the validation function:
    • We use Array.reduce() to iterate through the params array and calculate the sum of all weight properties.
    • We return true if the total sum is less than 100 (validation passes), or false if it's 100 or higher (validation fails).

Since your array is marked as .required(), we don't need to handle cases where params is undefined or empty here. If you ever need to adjust this, you could add a quick check like if (!params) return true; at the start of the test function to avoid errors.

This setup now enforces both of your requirements perfectly:

  1. Each individual weight value stays between 0 and 100 (from your existing .min(0).max(100) rules)
  2. The total sum of all weight values in the array is less than 100 (from the custom test)

内容的提问来源于stack exchange,提问作者Night Fury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:47:45