如何在自定义环回验证中提供动态消息? [英] How provide dynamic message in custom loopback validation?

查看:58
本文介绍了如何在自定义环回验证中提供动态消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处来自文档:

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.该怎么做?

Is there a way to modify message variable during validation? For example, this.name === 'bad' the message is Bad name but when this.name === 'very bad' the message should be Very Bad name. How this can be done?

推荐答案

突然有一个签名为errors.add(attr, message, code)addError方法,因此:

Suddenly there is a addError method with signature errors.add(attr, message, code), so:

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路径:

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": {
    "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": "..."
  }
}

这篇关于如何在自定义环回验证中提供动态消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆