Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing "contextual" data into validation method #51

Open
jamesplease opened this issue Apr 30, 2017 · 2 comments
Open

Passing "contextual" data into validation method #51

jamesplease opened this issue Apr 30, 2017 · 2 comments

Comments

@jamesplease
Copy link

jamesplease commented Apr 30, 2017

👋 @jfairbank !

I often need to validate a field based on some information outside of any of the fields being validated. That's what I mean by "contextual" data in this issue's title. For instance, in a web app that manages books, you may want the books to have a unique name. So to validate the name of one book, the validation method needs all books to know if there is a duplicate.

To do this, would you recommend putting this "extra" data in the object to validated, and then not adding any validation on that key within combineValidators?

To give an example, using the dog example from the docs:

const dogValidator = combineValidators({
  name: composeValidators(
    isAlphabetic,
    createValidator(
      message => (value, allValues) => {
        if (allValues.dogNames.indexOf(value) !== -1) {
          return message;
        }
      },

      field => `${field} must be unique`
    )
  )('Name'),

  age: isNumeric('Age')
});

const result = dogValidator({ name: 'larry', age: 'abc', dogNames: ['larry', 'kathryn'] });

Do you think this is fine, or do you have another suggestion on how best to do this? Thanks!


At first, I tried to do...

 createValidator(
  message => (value, allValues, dogNames) => {
    if (dogNames.indexOf(value) !== -1) {
      return message;
    }
  },

  field => `${field} must be unique`
)

const result = dogValidator({ name: 'larry', age: 'abc'}, ['larry', 'kathryn']);

but that didn't work :)

@jfairbank
Copy link
Owner

👋 @jmeas

I think your suggested workaround is fine, albeit a little cumbersome from an API standpoint. I do think that there could be value in passing contextual data as well. Ideally, it would easy to use manually like your example and also work well with redux-form.

I've been a little busy finishing up some features for another OSS project, but I hope to come back and work on revalidate some more soon. If you have any ideas, I'd love to see them and maybe a PR too :)

@jamesplease
Copy link
Author

👌 I'll whip up a PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants