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.
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: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.