Skip to content

Support custom validation and formatting functions #8

Description

@agarzola

Property values can be validated when they are set with a custom getter/setter function, but that’s cumbersome. It would be far better to pass a validation object with a validation method for each property that should be validated. This object should be included in the config object, like so:

const Author = new Model({
  name: 'attributes.full_name',
  age: 'attributes.age',
}, {
  validation: {
    name: function (candidate) {
      // function that returns true if `candidate` is valid, and false or an error
      // message if `candidate` is invalid; e.g.
      return (typeof candidate === 'string');
    },
    age: function (candidate) {
      // function that returns true if `candidate` is valid, and false or an error
      // message if `candidate` is invalid; e.g.
      if (typeof candidate !== 'number') {
        return new Error('The age property must be a number.');
      }

      if (candidate > 150) {
        return new Error('Nobody’s that old.');
      }

      return true;
    },
  },

These validation functions should, if present, be invoked before setting a value for the property after which they are named.

Similarly, a formatting object could also be supported for developers to declare methods that accept the value and return a new, formatted value. Useful for ensuring dates are formatted, for example.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions