shadcn_flutter icon indicating copy to clipboard operation
shadcn_flutter copied to clipboard

Use for loop instead of recursion in OrValidator

Open alistairmayo opened this issue 7 months ago • 2 comments

Using a for loop allows us to return early. We only need one success value from the child validators, so we return on the first success. If no validators succeed, we return the result of the first failed validator.

I was also running into a minor logic error in the existing implementation. I think it was checking for a Future<ValidationResult?> instead of a FutureOr<ValidationResult?>

alistairmayo avatar May 08 '25 10:05 alistairmayo

I don't think there is a problem with current OrValidator logic. The validate method can return a Future value that might returns null value (which means the form accepts the value) https://github.com/sunarya-thito/shadcn_flutter/blob/05078bcba244d0f42c39568baf70ad02d35bfbe3/lib/src/components/form/form.dart#L219 So this part does not mean anything https://github.com/sunarya-thito/shadcn_flutter/blob/05078bcba244d0f42c39568baf70ad02d35bfbe3/lib/src/components/form/form.dart#L222-L224 Take a look at this

final validator = ConditionalValidator(
      (value) async {
        await Future.delayed(const Duration(seconds: 2));
        return true;
      },
      message: 'a',
    ) |
    ConditionalValidator(
      (value) async {
        await Future.delayed(const Duration(seconds: 1));
        return false;
      },
      message: 'b',
    );

Based on your PR, the OrValidator will return the first sub validator ('a') because it returns a Future (non-null), and then completely ignore the 2nd sub validator ('b'). The form controller will wait for the first sub validator to complete, and since the first sub validator returns true (which means accept the form value), the form controller will mark the form value as valid even though the 2nd validator says otherwise. CMIIW

sunarya-thito avatar May 08 '25 10:05 sunarya-thito

Oh, I was using it directly: validator: OrValidator([otherValidator1, otherValidator2])

Let me take a look in more detail in a bit. Flutter async drives me a bit crazy.

alistairmayo avatar May 08 '25 11:05 alistairmayo

Hi, its been months and i hope youre doing okay!

For now, i'm going to close this PR. Feel free to open another PR if you want to keep the changes open for discussion! (I also pushed a new PR guidelines recently)

Thank you for your time, looking forward for your another pull request!

sunarya-thito avatar Nov 11 '25 20:11 sunarya-thito