Vue.js - Element UI - How to know the state of form validation

孤者浪人 提交于 2019-12-10 09:11:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!