6

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

The solution does not work in the case one of the field is not mandatory or does not have any rules to be validated against jsfiddle.net/wwyxt8es
You might want to change let fields = this.$refs.ruleForm2.fields; to let mandatoryFields = this.$refs.informationTabForm.fields.filter((f) => f.isRequired === true); Anyway, nice solution thanks
Also I can't find a good solution when a clereable dropdown is involved : jsfiddle.net/mab3q4f1
@Leo Updated the reduce function to take the field's required property into account. Not sure about the dropdown component, Looks like it doesn't play nice with the form's native events. Maybe you'll have to just specify the updateIsFormValidated handler on one of that component's events.
I struggled for the same reason for radio It seems that the validateState is not updated before the event change is triggered. So to validate select you better use visible-change event while for a radio it just does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.