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
。如何做到这一点?
答案 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.name
和error.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": "..."
}
}