Node Model Validation - Simplified Model Validator
npm install node-model-validation --save
const validate =const referenceModel =firstName:type: StringisRequired: truelastName:type: StringisRequired: trueage:type: NumberisRequired: truefavoriteFoods:type:isRequired: trueconst sampleModel =firstName: 'John'lastName: 'Smith'age: 27favoriteFoods:misc: 'random'let result =
validate returns an object with two properties
The model validation above outputs:
model:firstName: 'John'lastName: 'Smith'age: 27favoriteFoods:
The sample model validates without any errors and the misc field has been removed from the returned model. Since
misc was not defined in the referenceModel it is deemed erroneous and unneeded and can simply be removed from the model undergoing valdation without any errors.
If we can change the sampleModel in the first example to:
const sampleModel =firstName: 'John'lastName: 'Smith'age: 'twenty seven'favoriteFoods:
We now have a condition where we were expecting a number for the age value, but instead we have a String value. When this validates it will return the result below:
model:firstName: 'John'lastName: 'Smith'age: 'twenty seven'favoriteFoods:errors:property: 'age'type: 'number'message: 'Property age was of type string. Expected: number'isRequired: true
The property that offends the referenceModel is referenced in the errors array with the appropriate property attributes and a concise validation error message.