简体   繁体   English

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

[英]How provide dynamic message in custom loopback validation?

Here is from documentation: 下面是从文档:

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

Is there a way to modify message variable during validation? 有没有办法在验证期间修改message变量? For example, this.name === 'bad' the message is Bad name but when this.name === 'very bad' the message should be Very Bad name . 例如, this.name === 'bad'消息是Bad name但是当this.name === 'very bad' ,消息应该是Very Bad name How this can be done? 如何做到这一点?

Suddenly there is a addError method with signature errors.add(attr, message, code) , so: 突然有一个带有签名errors.add(attr, message, code)addError方法,所以:

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();
    }
});

This works, but keep in mind that you will have +1 custom code and message, see error.details.codes.name and error.details.messages.name paths from rough json below: error.details.codes.name ,但是请记住,您将获得+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": "..."
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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