在Sails.js中根据参数设置一个必需的属性

Make an attribute required based on param with Sails.js

本文关键字:一个 属性 js Sails 设置 参数      更新时间:2023-09-26

我有一个有两个属性的模型。一个叫userType,一个叫lastName

基本上我想做的是:如果userType是professor,那么lastName应该是必需的。

userType: {
  type: 'string',
  required: true,
  enum: ['professor', 'administrator']
},
lastName: {
  type: 'string',
  required: function() {
    return this.userType === 'professor';
  }
},

为什么不能将required作为函数传递?在水线文档中甚至有一个验证contains的例子。

如果不可能,是否有其他方法可以做到这一点?我不想在控制器上创建自定义验证,我想把一切都留给模型。甚至可以使用beforeValidate回调。

谢谢

根据sails文档http://sailsjs.org/documentation/concepts/models-and-orm/validations
您可以创建自己的验证,例如:

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
    }
  }
}