简体   繁体   中英

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

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

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

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