adopted-ember-addons / ember-changeset

Ember.js flavored changesets, inspired by Ecto
http://bit.ly/ember-changeset-demo
MIT License
431 stars 141 forks source link

Q: updating validations #644

Open basz opened 2 years ago

basz commented 2 years ago

For a contact component that contains multiple sub components (email, phone, etc) I create a single changeset with validations based on the added sub components. Data for each sub component is stored in a dictionary so the changeset responds to updates to individual sub component fields.

Sub components can be added and removed.

However when I add or remove a sub component I would need to update the validation map. However that can only be when instantiating the Changeset.

Is the a way to update an existing changeset with a new validation map?

sukima commented 2 years ago

I just ran into this and yes. You can mutatate the validationMap of a changeset after instantiating. It requires that a validationMap has previously been provided.

I have work in progress for a possible addon to allow validations to be added dynamically via modifiers. But the essential idea is that the modifier will run the following:

changeset.setDeep(changeset.validationMap, name, validators);

A caveat is that the mutation of that map will not trigger a validation thus a previously invalid field will remain invalid even if the validation was changed or removed. You will have to carefully choose the best time to run changeset.validate(name) and also .validate() will cause mutations and trigger rendering or an assert error if it changes as part of a render cycle. I had to wrap it:

requestAnimationFrame(() => changeset.validate(name));