Closed bsr203 closed 7 years ago
this avoided the error
const propValidator = combineValidators({
schema: composeValidators(
isRequired,
// isAlphabetic
)({ field: 'schema', multiple: true }),
name: isRequired({field: 'name'})
});
so, is field
is mandatory? is there a way to use the same as the object key?
Hi, @bsr203!
Maybe the key field
is a little misleading, but it's intended to be the label you want to use for your field in error messages. You always need to configure a validator whether that's the individual validator like the ageValidator
or the composed nameValidator
in the example below:
const ageValidator = isNumeric('Age');
const nameValidator = composeValidators(
isRequired,
isAlphabetic
)('Name');
ageValidator('abc'); // 'Age must be numeric'
nameValidator(''); // 'Name is required'
nameValidator('123'); // 'Name must be alphabetic'
Notice in this case, we just pass in the field label as a string when we configure. Then, later when we invoke the validators with incorrect values, we get back the error message. Note that it uses the supplied field label in the error message (i.e. Age and Name).
If you want to configure a composed validator to return multiple errors like you did, then you pass in options instead of a lone string when configuring a validator. In that case, you have to supply the field label via the field
key as you discovered. For example, changing our nameValidator
:
const nameValidator = composeValidators(
isRequired,
isAlphabetic
)({ multiple: true, field: 'Name' });
nameValidator(' '); // ['Name is required', 'Name must be alphabetic']
Your original error message was because you had to supply a field label or a custom error message via the message
key.
For your final question, though, because field
is for the field label, combineValidators
will not use the object key in place of the field label. Revalidate is fairly agnostic about what that object key represents, but you could say it's whatever key you use in your form, i.e. the name
attribute of your input field. Therefore, yes, field
or message
is required in your particular case. Note as I showed earlier that if you don't pass in the options object to a validator, then you could just supply field
via a string.
I encourage you to read through the docs more to better understand how the pieces of revalidate fit together. If anything appears confusing in the docs, then please raise an issue or even submit a PR to fix. I would definitely appreciate it!
thanks a ton for the detailed response. greatly appreciate it. been using it since and works great. Will report if I encounter any issue. thanks for your hard work on this and making validation more structured. Cheers.
Hi,
I couldn't make it work as in the Readme.
any help appreciated. thanks.
stack