2
votes

How can I define some validation rules depending on some conditions in request body.
For example, I want to validate that post description field is set only if the post is published (isPublished flag equals true), something like:

module.exports = function(Post) {
if(req.body.isPublished === true) {
    Post.validatesPresenceOf('description');
  }
}
2
Could you elaborate some more? - nitte93user3232918
@nitte93user3232918 I have elaborated more. - Ahmed Ismail

2 Answers

2
votes

Simply, you can use options parameter

Post.validatesPresenceOf('description', {if: 'isPublished'});

Ref: #validatable-validatespresenceof

2
votes

May be you are looking for something like this

Post.observe('before save',(ctx,next)=>{
  //if post is created
  if(ctx.isNewInstance) {
    if(ctx.instance.isPublished)
      Post.validatesPresenceOf('description');
  }
  //if post is updated
  else{
    if(ctx.data.isPublished)
      Post.validatesPresenceOf('description');
  }
return next();
})