formsy-react
formsy-react copied to clipboard
`validate` method workarounds?
Upgrading from 0.19, noticed that the "magical" validate()
method was removed.
Is there any new way to use props/state in validations?
Looking at issues and PRs from the old repo, I was only able to confirm that the method was removed on purpose, not accidentally. No trace of a reason that I could find.
It seems that a sane way to validate would be to only care about values. Do you have an example of a use case that would require the whole component context to be made available to the validation function?
I guess I was being lazy when writing components and eventually ended up with one generalized component that encapsulated the validation code/messages. It also seemed cleaner to do than it would have been to use validation props.
I took a look at the code before it was removed, and I didn't think it was that bad/unclean to have an onValidate
escape hatch
We also miss the old validate() method. We are validating not just based on the value, but also on the props of the current <MyInputWithPropsValidation/>
. I think, currently it is not possible to use the same validation pattern in two <MyInputWithPropsValidation/>
s with different props because Formsy will always take props of the last mounted <MyInputWithPropsValidation/>
.
I have done a small demo here: https://github.com/stevenpietzsch/formsy-react/tree/custom_validation
I adapted the custom-validation/app.js. You can see there, I used my own <MyInputWithPropsValidation/>
like this:
<MyInputWithPropsValidation name="customValidation1" maxValue={10} title="Custom validation with props" type="number" validations="customValidationWithProps" validationError="The value is not correct" />
<MyInputWithPropsValidation name="customValidation2" maxValue={20} title="Custom validation with props" type="number" validations="customValidationWithProps" validationError="The value is not correct" />
Just start the examples demo and see the result. The idea is to validate not only on the value, but also on the prop maxValue
. Unfortunately, both input fields are validated against the second maxValue (20). Thus, I can enter 12 in the first field, even though this is not allowed, because maxValue == 10.
Is there any workaround for validating against value + props?
If anyone wants to outline the spec / API documentation for this feature so that it's easily implementable, we can accept pull requests for it. I see several ways to accomplish this as-is:
-
customValidationWithProps:20
to pass a value to the validator - Make a wrapper component that passes down a validator
- Write a function that returns
{ maxValue: number, validations: function }
and ... that function on your props
Am I missing the complexity?