Reputation: 7344
i have a question about the validate prop. Suppose we (.....) In the component we define this:
<Field>
validate = {validate}
</Field>
Why cant we write validate={validate(value)} or why is not correct to write something like this: validate={()=> validate(value)}
Thanks!
Upvotes: 0
Views: 597
Reputation: 5010
The validate
prop on Field
takes a function (or an array of functions) which should be used to validate the incoming field value. So you can't write validate={ someCustomValidator(value) }
unless the someCustomValidator
function is a function you have defined that in turn returns a function.
Using validate={()=> someCustomValidator(value)}
should work, but doesn't make much sense in the context of your example (where does value
come from?). If you use validate={(value)=> someCustomValidator(value)}
instead, that makes more sense, but this is problematic because this will create a new function each time the component with the Field
re-renders. And according to the documentation:
Note: if the validate prop changes the field will be re-registered.
which is probably not what you want to happen.
So, using
// validation
const someCustomValidator = value => {
// give error roughly half of the time
return Math.random() < 0.5 ?
undefined : // validation is ok
'Validation failed'; // this will be available in meta.error
}
// somewhere else
<Field validate={someCustomValidator} />
is the correct way of using it. But note that Field
doesn't internally know what to do to display potential validation errors. That you have to solve yourself. See https://redux-form.com/7.0.4/examples/fieldlevelvalidation/ for an example.
Upvotes: 2