react-validation
react-validation copied to clipboard
Rules for dynamic names
The design of this library seems to use instance-specific information (like the name of a component) while trying to define abstract rules. For example, the password example:
password: {
// rule function can accept argument:
// components - components registered to Form mapped by name
rule: (value, components) => {
const password = components.password.state;
const passwordConfirm = components.passwordConfirm.state;
const isBothUsed = password
&& passwordConfirm
&& password.isUsed
&& passwordConfirm.isUsed;
const isBothChanged = isBothUsed && password.isChanged && passwordConfirm.isChanged;
if (!isBothUsed || !isBothChanged) {
return true;
}
return password.value === passwordConfirm.value;
}
Note that the names of component instances (in this case input components named "password" and "passwordConfirm") are being hardcoded. Given this design, how can one write rules which validate dynamic forms? For example, one might have a form in which one creates an unbounded number of new users. It would do this by having an "add" button somewhere in the form which creates a new set of fields corresponding with a new user. In this case, the names of the fields are dynamic (password1, password2, passwordConfirm1, passwordConfirm2) by necessity.
Is there any way to handle the example I describe?
The ability to add rules at runtime would solve this problem. However, although I can add rules to the rules collection, they don't seem to behave the way I expect. Is there some sort of registration or refresh method that needs to be run?