Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for empty strings in Joi (hapi.js)

I am using the Hapi.js framework along with Joi for data validation. I am trying to validate a JSON file using Joi. I have defined a schema and wanted to check whether the JSON file had all the fields from my schema.

Some of the string fields can be empty. In my schema file when I defined min as 0, it is saying name is a required field.

I am using the schema below:

    module.exports = {
      "name": { "type": "string", "min": 0, "max": 30},
      "age": { "type": "number", "min": 1, "max": 36},
      "dob": { "type": "string", "min": 0, "max": 100 }
    }

How can I modify this schema to handle empty strings?

like image 339
user3656330 Avatar asked Apr 21 '16 09:04

user3656330


1 Answers

If you want to allow empty strings, you need to explicitly allow them with joi.string().allow('').

var joi = require('joi');

var schema = joi.object().keys({
    name: joi.string().min(0).allow('').allow(null),
    age: joi.number().min(1).max(36),
    dob: joi.string().min(0).max(100)
});

var obj = {
    name: '',
    age: '18',
    dob: '11/11/2998'
};

var result = joi.validate(obj, schema);

console.log(JSON.stringify(result, null, 2));

The output of the above schema after using joi.describe is:

{
  "type": "object",
  "children": {
    "name": {
      "type": "string",
      "valids": [
        "",
        null
      ],
      "rules": [
        {
          "name": "min",
          "arg": 0
        }
      ]
    },
    "age": {
      "type": "number",
      "invalids": [
        null,
        null
      ],
      "rules": [
        {
          "name": "min",
          "arg": 1
        },
        {
          "name": "max",
          "arg": 36
        }
      ]
    },
    "dob": {
      "type": "string",
      "invalids": [
        ""
      ],
      "rules": [
        {
          "name": "min",
          "arg": 0
        },
        {
          "name": "max",
          "arg": 100
        }
      ]
    }
  }
}
like image 127
Cuthbert Avatar answered Nov 09 '22 21:11

Cuthbert