如何使用Yup为数组对象的weight属性设置验证:实现单个值范围校验及总和小于100的校验
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 theYup.array()definition forparams. - 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 theparamsarray and calculate the sum of allweightproperties. - We return
trueif the total sum is less than 100 (validation passes), orfalseif it's 100 or higher (validation fails).
- We use
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:
- Each individual
weightvalue stays between 0 and 100 (from your existing.min(0).max(100)rules) - The total sum of all
weightvalues in the array is less than 100 (from the custom test)
内容的提问来源于stack exchange,提问作者Night Fury

