下面的模式允许我将optionalField设置为option1,但是如果将值设置为option2,则optionalField可以设置为用户想要的任何东西。相反,如果value设置为option1以外的任何东西,并且optionalField被传入,我希望验证失败。
const validValues = ['option1', 'option2']
const sampleSchema = new mongoose.Schema({
value: {
type: String,
enum: validValues,
required: true
}
optionalField: {
type: Number,
required: function() { return this.value === 'option1' }
// validation should fail if this property is passed in when value is anything but option1
}
})Joi有一个很好的方法可以使用Joi.forbidden()来实现这一点。
const validValues = ['option1', 'option2']
const schema = Joi.object({
value: Joi.string().valid(...validValues).required(),
optionalField: Joi.string().when('value', { is: 'option1', then: Joi.required() otherwise: Joi.forbidden() })
})如果我使用此模式进行验证,并将optionalField传递给Joi,除非value是option1,否则验证将失败。
我希望能在猫鼬身上找到一种方法来实现同样的目标。
谢谢!
发布于 2019-12-25 08:13:46
您可以这样使用自定义验证器:
optionalField: {
type: Number,
required: function() {
return this.value === "option1";
},
validate: {
validator: function(v) {
console.log({ v });
return !(this.value !== "option1" && v.toString());
},
message: props =>
`${props.value} optionalField is forbidden when value is not option1`
}
}样本路线:
router.post("/sample", (req, res) => {
const sample = new Sample(req.body);
sample
.save()
.then(doc => res.send(doc))
.catch(err => res.status(500).send(err));
});投入1:
{
"value": "option2",
"optionalField": 11
}结果1:(错误)
{
"errors": {
"optionalField": {
"message": "11 optionalField is forbidden when value is not option1",
"name": "ValidatorError",
"properties": {
"message": "11 optionalField is forbidden when value is not option1",
"type": "user defined",
"path": "optionalField",
"value": 11
},
"kind": "user defined",
"path": "optionalField",
"value": 11
}
},
"_message": "Sample validation failed",
"message": "Sample validation failed: optionalField: 11 optionalField is forbidden when value is not option1",
"name": "ValidationError"
}投入2:
{
"value": "option2"
}成果2:(成功)
{
"_id": "5e031b473cbc432dfc03fa0e",
"value": "option2",
"__v": 0
}投入3:
{
"value": "option1"
}结果3:(错误)
{
"errors": {
"optionalField": {
"message": "Path `optionalField` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `optionalField` is required.",
"type": "required",
"path": "optionalField"
},
"kind": "required",
"path": "optionalField"
}
},
"_message": "Sample validation failed",
"message": "Sample validation failed: optionalField: Path `optionalField` is required.",
"name": "ValidationError"
}投入4:
{
"value": "option1",
"optionalField": 11
}成果4:(成功)
{
"_id": "5e031ba83cbc432dfc03fa10",
"value": "option1",
"optionalField": 11,
"__v": 0
}https://stackoverflow.com/questions/59474717
复制相似问题