json-schema-validator custom message

New Bee picture New Bee · Nov 4, 2016 · Viewed 12.6k times · Source

I am using json-schema-validator2.2.6 library to validate my json against json schema. The problem is that it gives generic error messages that are not relevant to me. I want to send custom message or code to user.

Do we have any option like this :

"properties": {
        "myKey": {
            "type": "string"
            **"errorMessage" : "My error message"**
        },
}

Or any other way by which I can provide custom error message?

Answer

Supermacy picture Supermacy · Jul 20, 2017

You can create Custom Error Messages in JSON Schema. Sort Of!(In NodeJS). Lets take an Example - We have to check a key 'DOB' in JSON which should is a required field and it should be in format 'dd-mmm-yyyy'.
Now we have to use two validation in JSON. First, It should be present and it should follow the pattern of `dd-mmm-yyyy'

Now JSON Schema would be

{
"id": "DOBChecker",
"type": "object",
"properties": {
    "DOB": {
        "type": "string",
        "required": true,
        "pattern": "/^(([1-9]|0[1-9]|1[0-9]|2[1-9]|3[0-1])[-](JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC)[-](\d{4}))$/i",
        "message": {
            "required": "Date of Birth is Required Property",
            "pattern": "Correct format of Date Of Birth is dd-mmm-yyyy"
        }
    }
}

Now If you have got the error while validations. You will get the whole schema back at errors key array and in that access schema object. The Schema Object will contain exactly same keys as the schema defined above.
You can now access it . The failed Validation name will be in the 'name' key. Now you can access your custom Message using
schema.message[name]