shakacode / re-formality

Form validation tool for reason-react
https://re-formality.now.sh
MIT License
244 stars 35 forks source link

Global Form Validator #45

Closed lukashambsch closed 5 years ago

lukashambsch commented 5 years ago

Is there a way to create a global form validator?

My use case is with a form that just requires any one of the fields to be completed for it to be valid. I can put the validation on a single field, but then the error message makes it look like that field is required.

My thought was making field in the validator optional. So you could do something like this:

let validator = {
      field: None,
      strategy: Strategy.OnFirstSuccessOrFirstBlur,
      dependents: Some([One, Two, Three, Four, Five]),
      validate: ({one, two, three, four, five}) =>
        switch (one, two, three, four, five) {
        | ("", "", "", "", "") =>
          Error("You must complete one of the fields.")
        | _ => Ok(Valid)
        },
    };

If there isn't a way now, do you have any suggestions on the best way to do it?

Thanks!

alex35mil commented 5 years ago

@lukashambsch Your validator looks good to me and I think you can solve UX part of the issue by not displaying errors next to specific fields but somewhere where your users would consider an error as global to the form. Then, to figure out when to show an error you can just check results for each field and if all of them are in an error state -> show global error. Does it work for you?

lukashambsch commented 5 years ago

The validator I showed above doesn't work for me because field is defined as None. It seems like field is expecting a value instead of an option. I guess I could just superficially associate it to a field, but that would make that field's specific validation a little more difficult.

alex35mil commented 5 years ago

Validator receives a state of a form, i.e. what you defined as a state type.

lukashambsch commented 5 years ago

Got it. So for the field it takes in what I define as the field type. That makes sense. Thanks!