简体   繁体   中英

Make an attribute required based on param with Sails.js

I have a model with two attributes. One called userType and one called lastName .

Basically what I want to do is: if userType is professor then lastName should be required.

userType: {
  type: 'string',
  required: true,
  enum: ['professor', 'administrator']
},

lastName: {
  type: 'string',
  required: function() {
    return this.userType === 'professor';
  }
},

Why can't I pass required as a function? In the waterline documentation there is even an example with the validation contains .

If not possible, does it have any other way to do this? I don't want to create custom validations on the controller, I want to leave everything to the model. Maybe even use the beforeValidate callback.

Thanks

According to sails documentation http://sailsjs.org/documentation/concepts/models-and-orm/validations
You could make your own validations, something like :

module.exports = {
  types: {
    isProfessor: function(lastName){
      return (this.userType === 'professor' && !lastName)? false: true;
    }
  },
  attributes:{
    userType: {
      type: 'string',
      required: true,
      enum: ['professor', 'administrator']
    },
    lastName: {
      type: 'string',
      isProfessor: true
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM