react-validation
react-validation copied to clipboard
Pass current component to validation rule?
I have a form with a variable number of pairs of input fields. If one item in a pair has a value, the other needs to have a value too.
The form looks something like this:
<Form>
<Input type='text' name='input1' data-paired-with='input2' validations={['paired']} />
<Input type='text' name='input2' data-paired-with='input1' validations={['paired']} />
<Input type='text' name='input3' data-paired-with='input4' validations={['paired']} />
<Input type='text' name='input4' data-paired-with='input3' validations={['paired']} />
<!-- other stuff here -->
</Form>
The code that invokes a rule only passes the value and the set of components in, so you don't know what the current component being validated is, only it's value:
if (!rules[validations[i]].rule(component.state.value, this.components)) {
If it passed the current component in too:
if (!rules[validations[i]].rule(component.state.value, this.components, component)) {
I could perform this sort of validation:
{
paired: {
rule: (value, components, component) => {
// find paired component
const other = components[component.props['data-paired-with']]
if (!value && other.state.value) {
return false
}
return true
},
hint: value => {
// return error message
}
}
}
Is there any chance of passing the current component to the validation rule?
Hi! When I look at const password = (value, props, components)
from the example in the readme, it seems to me that props
now serves this purpose. Is that correct (and this ticket is done) or am I misunderstanding the function of props
? Thanks!