FiguredLimited / vue-mc

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

requiredIf problem #123

Closed fakocher closed 4 years ago

fakocher commented 5 years ago

Hello everybody,

I created my own requiredIf validator that says an attribute is required if another attribute is true, like the one from Vuelidate.

const requiredIf = (other) => 
{
    return rule({
        name: 'requiredIf',
        test: (value, attribute, model) => {
           return !(isNil(value) || value === '') || !model.get(other)
        },
        data: {other},
    });
};

My problem is, the attribute this rule is set on is not validated if the "other" attribute is changed. To cope with that, I watch the "other" attribute changes and run model.validate(). It works, but it's validating every attribute of the model when it should only validate one, and I have to document this weird behavior for my team.

Is there a way to say in a custom rule that the attribute should be validated when another specific attribute is changed ?

Thanks in advance for your answers. Jeremy

rtheunissen commented 5 years ago

Is there a way to say in a custom rule that the attribute should be validated when another specific attribute is changed?

Not currently, but I'd be happy to explore the option to include that. In the meantime, you can pass a parameter name to validate, like this:

model.validate('name');

model.validate(['name', 'other']);

See https://github.com/FiguredLimited/vue-mc/blob/master/src/Structures/Model.js#L683

fakocher commented 5 years ago

Thank you for your answer. We'll use your solution so not all the fields are validated (the model has lots of fields). Have a good day!