Phoenix Dev
Phoenix Dev

Reputation: 457

Role based validation not working in loopback

I have two roles and want to apply different data validation rules on the incoming post request based on a role field in the incoming data ie. if posted role is of admin then validate whether input has name field and if role is user, validate if input has age. I wrote validation code in beforeRemote hook of create method like:

 if (role === "admin") {
      Members.validatesPresenceOf('name');
      next();
 } else {
      Members.validatesPresenceOf('age');
      next();
 }

For the first request, if role is admin, validation works and catches if name is not present in input. But for the next request if role is user, still validation error occurs for name field and not age. Then if I restart node server and try first with user role, the age validation is caught but then for all subsequent requests age validation will be checked irrespective of role. What could be the problem? If there any other method to achieve this, please let me know. Thanks in advance!

Upvotes: 0

Views: 139

Answers (1)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

Validations are permanent for models. This way is not working.

You need to create a custom validator :

Members.validateAsync('name', function(err, done){
  var role = getRole();
  if(role === 'admin'){
    if(!this.name) err();
  }
  done();
}, {message: 'name should be filled'});

Members.validateAsync('age', function(err, done){
  var role = getRole();
  if(role !== 'admin'){
    if(!this.age) err();
  }
  done();
}, {message: 'age should be filled'});

Upvotes: 3

Related Questions