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

feat: validated changeset #649

Closed snewcomer closed 2 years ago

snewcomer commented 2 years ago

ref https://github.com/validated-changeset/validated-changeset/pull/168

Minor bump. Just adding a new changeset to the mix. See how people like it.

Limited API compared to the original Changeset.

ValidatedChangeset

See yup example

import Component from '@glimmer/component';
import { ValidatedChangeset } from 'ember-changeset';
import { action, get } from '@ember/object';
import { object, string } from 'yup';

class Foo {
  user = {
    name: 'someone',
    email: 'something@gmail.com',
  };
}

const FormSchema = object({
  cid: string().required(),
  user: object({
    name: string().required(),
    email: string().email(),
  })
});

export default class ValidatedForm extends Component {
  constructor() {
    super(...arguments);

    this.model = new Foo();
    this.changeset = ValidatedChangeset(this.model);
  }

  @action
  async setChangesetProperty(path, evt) {
    this.changeset.set(path, evt.target.value);
    try {
      await this.changeset.validate((changes) => FormSchema.validate(changes));
      this.changeset.removeError(path);
      await this.model.save();
    } catch (e) {
      this.changeset.addError(e.path, { value: this.changeset.get(e.path), validation: e.message });
    }
  }

  @action
  async submitForm(changeset, event) {
    event.preventDefault();

    changeset.execute();
  }
}