I am using Ajv for validating my JSON data. I am unable to find a way to validate empty string as a value of a key. I tried using pattern, but it does not throw appropriate message.
Here is my schema
{
"type": "object",
"properties": {
"user_name": { "type": "string" , "minLength": 1},
"user_email": { "type": "string" , "minLength": 1},
"user_contact": { "type": "string" , "minLength": 1}
},
"required": [ "user_name", 'user_email', 'user_contact']
}
I am using minLength to check that value should contain at least one character. But it also allows empty space.
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
The primary strength of JSON Schema is that it generates clear, human- and machine-readable documentation. It's easy to accurately describe the structure of data in a way that developers can use for automated validation. This makes work easier for developers and testers, but the benefits go beyond productivity.
import Ajv from "ajv"; import { inspect } from "util"; const ajv = new Ajv({ allErrors: true }); export const validatorFactory = (schema) => { const validate = ajv. compile(schema); const verify = (data) => { const isValid = validate(data); if (isValid) { return data; } throw new Error( ajv.
allOf: (AND) Must be valid against all of the subschemas. anyOf: (OR) Must be valid against any of the subschemas. oneOf: (XOR) Must be valid against exactly one of the subschemas.
You can do:
ajv.addKeyword('isNotEmpty', {
type: 'string',
validate: function (schema, data) {
return typeof data === 'string' && data.trim() !== ''
},
errors: false
})
And in the json schema:
{
[...]
"type": "object",
"properties": {
"inputName": {
"type": "string",
"format": "url",
"isNotEmpty": true,
"errorMessage": {
"isNotEmpty": "...",
"format": "..."
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With