Add the ability to inject rules to descendant input elements
See original GitHub issueVersions:
- VueJs: 2.3.4
- Vee-Validate: 2.0.0-rc.5
Description:
With the recent change introduced by #468, it’s now possible to create one $validator
for the whole <form>
, and injecting this instance to all of its descendants.
The next step I would like to see is the ability to define validation rulesets for the whole <form>
, and let each field picks up its corresponding validation rules from the rulesets. We can probably use provide/inject
mechanism for this similar to #468.
In short, instead of doing tedious typing like this:
<template>
<vee-form>
<!-- here, we need to type out expression for every v-validate being declared -->
<!-- for bigger form, it can be tedious and error-prone -->
<vee-input name="email" title="Email"
v-model="email" v-validate="'required|email'" />
<vee-input name="password" title="Password" type="password"
v-model="password" v-validate="some.path.to.password.rules" />
<!-- more typing for every v-validate added -->
...
<el-button size="large" type="primary" @click="validateForm()">Log-in</el-button>
</vee-form>
</template>
It’d be great if we can achieve the same behavior with the following:
<template>
<vee-form>
<!-- here we rely on dependency injection, thus v-validate can be empty -->
<!-- the component simply looks up its rules from rulesets using its "name" attribute -->
<vee-input name="email" title="Email"
v-model="email" v-validate />
<vee-input name="password" title="Password" type="password"
v-model="password" v-validate />
...
<el-button size="large" type="primary" @click="validateForm()">Log-in</el-button>
</vee-form>
</template>
<script>
export default {
$validates: true,
provide: {
// rulesets for the whole form
rulesets: {
email: 'required|email',
password: 'required',
},
},
...
};
</script>
By relying on empty v-validate
, we still keep most of the directive’s logic intact, and thus we still benefit from input change listeners that directive provides. I did some tinkering with the code (not fully working yet), and the main change we need probably resides in getRules()
function in utils.js
:
// add "component" param
export const getRules = (expression, value, el, component) => {
if (!expression) {
/* CHANGES MADE HERE */
if (component.name && component.rulesets) {
return component.rulesets[component.name];
} else {
return getDataAttribute(el, 'rules');
}
}
if (typeof value === 'string') {
return value;
}
if (~['string', 'object'].indexOf(typeof value.rules)) {
return value.rules;
}
return value;
};
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:7 (4 by maintainers)
@logaretm Hi, have you found anything regarding the interaction between
$validates
andprovide
property? Once it is solved this issue should be ready for a merge.I see, at least we now know we can use both
$validates
andprovide
in one component with the current implementation. I’ll try to play around on my end this weekend as well.