Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json-schema-validator custom message

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?

like image 354
New Bee Avatar asked Nov 04 '16 13:11

New Bee


People also ask

How do I customize error messages in JSON Schema?

According to this from the JSON-schema-form docs on customizing error messages, the only way to do this would be to define a transform function that receives the list of JSON Schema errors and returns a new list.

Does JSON have schema validation?

JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.

How does JSON Schema validation work?

JSON Schema Validation: The JSON Schema Validation specification is the document that defines the valid ways to define validation constraints. This document also defines a set of keywords that can be used to specify validations for a JSON API. In the examples that follow, we'll be using some of these keywords.


1 Answers

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]

like image 200
Supermacy Avatar answered Sep 28 '22 05:09

Supermacy