fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
5.94k stars 181 forks source link

Validation Recheck Not Triggered for Other Indices or Fields in Array When Using forward with a Specific Index #820

Open yamatohagi opened 1 week ago

yamatohagi commented 1 week ago

The issue arises when using the forward function in the validation schema with [0, 'maleGuestNum']. It seems that validation does not trigger revalidation for other indices or fields like femaleGuestNum when an error is detected in maleGuestNum. This results in the validation only being applied to the first guest and does not account for other guests in the array or other fields. I would like validation to trigger rechecks for all guests and fields (e.g., femaleGuestNum or unknownGenderNum) when any part of the guest data is changed.

guests: pipe(
  array(
    object({
      guestId: optional(pipe(string(), minLength(1, 'This field is required')), ''),
      maleGuestNum: pipe(
        unknown(),
        transform((input) => Number(input)),
      ),
      femaleGuestNum: pipe(
        unknown(),
        transform((input) => Number(input)),
      ),
      unknownGenderNum: pipe(
        unknown(),
        transform((input) => Number(input)),
      ),
    }),
  ),

  forward(
    check((guest) => {
      // Check total number of guests
      const totalGuests = guest.reduce((acc, guest) => acc + guest.maleGuestNum + guest.femaleGuestNum + guest.unknownGenderNum, 0);

      // If total number of guests is 0, trigger error
      return totalGuests > 0;
    }, 'Total number of guests cannot be zero'),
    [0, 'maleGuestNum'], // This only validates for the first guest's 'maleGuestNum'
  ),
),

Problem: The issue occurs when specifying [0, 'maleGuestNum'] in the forward function. The validation does not trigger revalidation for other guest indices or other fields like femaleGuestNum or unknownGenderNum. I expect the validation to recheck all fields and all guest entries, but it only checks the first guest's maleGuestNum field, leaving the rest unchecked unless manually updated.

Thank you for your time and attention to this issue. I appreciate any insights or solutions that could help resolve this validation behavior. Looking forward to your feedback!

fabian-hiller commented 1 week ago

I don't understand everything. Can you explain in very simple terms what is the current state and what is the expected behavior or output? Feel free to share a playground link with an example. Also keep in mind that there are many more specific validation actions like checkItems and everyItem that can be used with array.