Reputation: 9859
I need to validate nested form data in Vue Element. The example is pretty same with my code. The only difference that dynamicValidateForm
is wrapped in MainForm
. But I can't get it work.
https://jsfiddle.net/mwxaqhn7/
Here is my code:
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<div id="app">
<el-form :model="MainForm.dynamicValidateForm" ref="MainForm.dynamicValidateForm" label-width="120px" class="demo-dynamic">
<el-form-item
v-for="(domain, index) in MainForm.dynamicValidateForm.domains"
:label="'Domain' + index"
:key="domain.key"
:prop="'domains.' + index + '.value'"
:rules="rules"
>
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('MainForm')">Submit</el-button>
<el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('MainForm.dynamicValidateForm')">Reset</el-button>
</el-form-item>
</el-form>
</div>
App:
new Vue({
el: '#app',
data: {
MainForm:
{
dynamicValidateForm: {
domains: [{
key: 1,
value: ''
}],
},
},
rules: {
value: [
{ required: true, message: 'Please input'},
],
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
addDomain() {
this.MainForm.dynamicValidateForm.domains.push({
key: Date.now(),
value: ''
});
},
Validate(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
}
})
I would like to validate all nested elements with same rule.
I also tried to do it in another way, but got another error https://jsfiddle.net/st56h3ky/
Error: please transfer a valid prop path to form item!
Upvotes: 2
Views: 3718
Reputation: 31
change the :rules=rules
with
:rules="rules.value"
and add change submit form button to
<el-button type="primary" @click="submitForm('MainForm.dynamicValidateForm')">Submit</el-button>
like in the following code
<el-form :model="MainForm.dynamicValidateForm" ref="MainForm.dynamicValidateForm" label-width="120px" class="demo-dynamic">
<el-form-item
v-for="(domain, index) in MainForm.dynamicValidateForm.domains"
:label="'Domain' + index"
:key="domain.key"
:prop="'domains.' + index + '.value'"
:rules="rules.value"
>
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('MainForm.dynamicValidateForm')">Submit</el-button>
<el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('MainForm.dynamicValidateForm')">Reset</el-button>
</el-form-item>
</el-form>
Upvotes: 2