Validating nested objects with Joi

北战南征 提交于 2020-08-07 05:30:38

问题


How to validate this object using joi? Im using Joi with Hapi api.

    {
    "email":"rambo@gmail.com",
    "password":"abc123",
    "active":"",
    "details": {
        "firstName": "Rambo",
        "lastName": "Comando",
        "phoneNumber": "5554446655",
        "billing":{
            "firstName": "",
            "lastName": "",
            "phoneNumber": "",
            "address": "",
            "adress2": "",
            "postalCode": "",
            "city": "",
            "state": "",
            "country": "",
            "stripeId": ""
        }
     }
  }

I tried doing like this, but it is not working. What is the correct way of doing this?

payload: {
        email: Joi.string().email().required(),
        password: Joi.string().alphanum().min(8).max(30).required(),
        active: Joi.boolean(),
        details: Joi.object().keys({
            firstName: Joi.string().max(50),
            lastName: Joi.string().max(50),
            phoneNumber: Joi.number().integer().min(10).max(11),
            billing : Joi.object().keys({
                firstName: Joi.string().max(50),
                lastName: Joi.string().max(50),
                phoneNumber: Joi.string().integer().min(10).max(11),
                address: Joi.string().alphanum(),
                adress2: Joi.string().alphanum(),
                postalCode: Joi.string().alphanum(),
                city: Joi.string(),
                state: Joi.string(),
                country: Joi.string(),
                stripeId: Joi.string().alphanum()
            })
        })
    }

Im not sure where im missing things up.


回答1:


There is an error in your code, at this line:

phoneNumber: Joi.string().integer().min(10).max(11),

The Node.js throws exception because of it:

TypeError: Joi.integer is not a function

If you change that to either string() or number() everything will work as it should:

phoneNumber: Joi.number().min(10).max(11),

It's quite obvious so I'm just wondering, how you've missed it? Everything else with your Joi schema seems alright.



来源:https://stackoverflow.com/questions/46284691/validating-nested-objects-with-joi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!