简体   繁体   中英

Joi field validation base on a set of values of another field

I am trying to validate field in an object based on a set of values of another field. Assuming my object has to fields, field1 and field2 . Field one can take values A, B, C, D, E, F, H, I. Now say if field1 is any of the values; A, B, C, H, then field2 should be null. How do I do this. I think it should have the synthax below but I don't know how to implement it completely.

const mySchema = Joi.object({
   field1: Joi.string().valid('A','B','C','D','E','F','H','I').required(),
   field2: Joi.when('field1', is: <A or B or C or H> then: <field2 should be null> otherwise: Joi.date().required())
});

NB: I am using "@hapi/joi": "^17.1.1"

I finally got it by trying:

const Joi = require("@hapi/joi");

const schema = Joi.object({
    field1: Joi.string().valid('A', 'B', 'C', 'D', 'E', 'F', 'H', 'I').required(),
    field2: Joi.when('field1', {
        is: Joi.string().valid('A', 'B', 'C', 'H'),
        then: Joi.valid(null),
        otherwise: Joi.date().required(),
    }),
});

const validation = [schema.validate({ field1: 'B', field2: null }), schema.validate({ field1: 'E', field2: null }),
                    schema.validate({ field1: 'E', field2: Date() }), schema.validate({ field1: 'A', field2: Date() })];

validation.forEach((v)=>{
    if(v.error){
        console.log(JSON.stringify(v.error));
    }else{
        console.log(JSON.stringify(v.value));
    }
});

Here is the output.

{"field1":"B","field2":null}
{"_original":{"field1":"E","field2":null},"details":[{"message":"\"field2\" must be a valid date","path":["field2"],"type":"date.base","context":{"label":"field2","value":null,"key":"field2"}}]}
{"field1":"E","field2":"2020-05-20T12:26:48.000Z"}
{"_original":{"field1":"A","field2":"Wed May 20 2020 13:26:48 GMT+0100 (West Africa Standard Time)"},"details":[{"message":"\"field2\" must be [null]","path":["field2"],"type":"any.only","context":{"valids":[null],"label":"field2","value":"Wed May 20 2020 13:26:48 GMT+0100 (West Africa Standard Time)","key":"field2"}}]}

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