Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom validation and formatting functions #8

Open
agarzola opened this issue Jun 16, 2018 · 0 comments
Open

Support custom validation and formatting functions #8

agarzola opened this issue Jun 16, 2018 · 0 comments
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed

Comments

@agarzola
Copy link
Member

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.

@agarzola agarzola added help wanted Extra attention is needed enhancement New feature or request good first issue Good for newcomers labels Jun 16, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant