Saturday, June 24, 2017

Run validation for one field in Mongoose model

Leave a Comment

I need to run validators for some particular field without affecting model validation state. How can this be done?

The context for this is that there is validation hook that is intended for validating one field (foo) but it requires to be sure that (bar) is ok first.

... bar: {   required: true,   type: Number,   min: 2,   max: 10,   validator: isInteger } ...  function validateFoo(foo, bar) {   // the code below will throw if bar is not an integer between 2 and 10   ... }  schema.pre('validate', function (next) {   if (/* check if model.bar is valid */) {     if (!validateFoo(model.foo, model.bar)) {       model.invalidate('foo', 'foo is invalid');     }   } else {     model.invalidate('foo', 'foo is invalid because of bar');   }    next(); }); 

Doing this by not using existing bar schema validators will result in WET code:

schema.pre('validate', function (next) {   // WET!   if (model.bar >= 2 && model.bar <= 10 && isInteger(model.bar))   ... } 

1 Answers

Answers 1

You should take a look at the Custom Validators section here : http://mongoosejs.com/docs/validation.html

This way, the bar validator will run before your pre-validate hook.

Also, I don't see why the validation of one field would rely on another. Perhaps, you should be a bit more explicit about what you intend to do.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment