如何在自定义环回验证中提供动态消息?

时间:2017-07-07 06:45:33

标签: javascript loopbackjs

Here来自文档:

User.validate('name', customValidator, {message: 'Bad name'});
function customValidator(err) {
    if (this.name === 'bad') err();
});
var user = new User({name: 'Peter'});
user.isValid(); // true
user.name = 'bad';
user.isValid(); // false

有没有办法在验证期间修改message变量?例如,this.name === 'bad'邮件为Bad name,但this.name === 'very bad'时邮件应为Very Bad name。如何做到这一点?

1 个答案:

答案 0 :(得分:0)

突然有addError方法带有签名errors.add(attr, message, code),所以:

User.validate('name', customValidator);
function customValidator(err) {
    if (this.name === 'bad') {
        this.errors.add('name', `Name is bad`, 'name.bad')
        err();
    }
    if (this.name === 'very bad') {
        this.errors.add('name', `Name is very bad`, 'name.very.bad')
        err();
    }
});

这样做有效,但请注意,您将拥有 +1 custom代码和消息,请参阅以下粗略json中的error.details.codes.nameerror.details.messages.name路径:

{
  "error": {
    "statusCode": 422,
    "name": "ValidationError",
    "message": "The `Entity` instance is not valid. Details: `name` Name is very bad (value: very bad).",
    "details": {
      "context": "Entity",
      "codes": {
        "name": [
          "name.very.bad",
          "custom"
        ],
        },
      "messages": {
        "name": [
          "Name is very bad",
          "is invalid"
        ]
      }
    },
    "stack": "..."
  }
}