FiguredLimited / vue-mc

Models and Collections for Vue
https://vuemc.io
MIT License
626 stars 98 forks source link

Event `change` is emited without running validation even if option `validateOnChange` is set #110

Open ozakha opened 5 years ago

ozakha commented 5 years ago

vue version: 2.6.6 vue-mc version: 0.5.0

Expected I create instance of model with option validateOnChange=true I listen the event change on this model as fallow:

this.someModel.on('change', ({attribute, previous, value}) => {
    ...
});

I do changes with any attribute and expect that validation is executed before I intercept change event.

Why I need this It is regular situation when form inputs are distributed between tabs: wizards for example. Also I have couple models instead of one. And I need to manage whole form state, means, from each model and highlight respectively tab. As well as reset tab error highlight when user did changes to correct data.

I found respectively code here

rtheunissen commented 5 years ago

So we should validate before we emit the change event? Sounds good to me. Would the change event then not be fired if the value is not valid?

ozakha commented 5 years ago

@rtheunissen good question I think that, normally, change process is independent from validation, but they work in chain together.

rtheunissen commented 5 years ago

What if we passed a 4th parameter called "valid" to change? I'm stuck on deciding whether a change event should be fired if the value is not valid. I think yes, but would that solve your problem (making validation run first, then change event?).

Also keep in mind that validation rules can be async as well, in which case I don't think we want to wait for validation before we fire the change. I think that how it is right now (emit change asap, then validate) is the most natural.

Can you maybe explain a bit better what issue you're facing with the forms? How would validating before the change event solve your problem?

ozakha commented 5 years ago

@rtheunissen I believe that change event should be triggered if any change of any attribute happened. In same time validation must be executed (regarding to config) before change event is triggered.

Currently, I found unstable work of validation with validationOnChange = true, so I have to force check it in this way.

...
created() {
    this.someModel.on('change', async ({attribute}) => {
        await this.someModel.validateAttribute(attribute);
        this.tabList.general.hasErrors = _.keys(this.someModel.errors).length > 0;
    });
}
...

instead of doing so

...
created() {
    this.someModel.on('change', () => {
        this.tabList.general.hasErrors = _.keys(this.someModel.errors).length > 0;
    });
}
...