问题
I'm using, vue-js
and element-ui
I would like to check the state of the validation of a form without having to click on a submit button
Example
https://jsfiddle.net/nw8mw1s2/
Steps to reproduce
Click on each field
The verification is triggered with the blur
Start filling the different inputs
Question
How can I do so when the last input is validated, isFormValidated
turns to true
.
In other words, how can I say "If there is no field with the state error, then turn valudateState
to true"
Tips
I guess we can check the validateState
of each formItem
of the form. But I do not see how to do it concretely.
回答1:
I would create a new method (say updateIsFormValidated
), and bind it to the native focusout
event of the form:
<el-form :model="ruleForm2" @focusout.native="updateIsFormValidated" ...>
This method will fire each time any of the inputs in the form loses focus. It will attempt to check that each field in the form component has successfully been validated, firing each 100 milliseconds if the validation status of any of the form items is still pending:
updateIsFormValidated() {
let fields = this.$refs.ruleForm2.fields;
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => { this.updateIsFormValidated() }, 100);
} else {
this.isFormValidated = fields.reduce((acc, f) => {
let valid = (f.isRequired && f.validateState === 'success');
let notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, true);
}
}
Here's a working fiddle.
来源:https://stackoverflow.com/questions/44399041/vue-js-element-ui-how-to-know-the-state-of-form-validation