How can I validate null and non-empty string URIs?

138 views Asked by At

I am having a URI value where it can accept null values and string URI values only, and the URI value cannot be empty.

I tried with several implementations and it did not work.

I am using AJV validation library version number 6.12.6.

These are my try outs:

agreementURL: {
   "type": ["string", "null"],
   "if": {
     "type": "string"
   },
   "then": {
     "format": "uri",
   }
 }, 
2

There are 2 answers

0
V2rson On

in ajv schema file we can define a function according to our requirements so inorder to solve this issue , i created a function where it allows a null and string uri format .

ajv.addKeyword('isAllowNullAndURI', {
  type: 'string',
  validate: function(schema, data) {
    if (data === null) {
      return true; 
    }
   
    if (typeof data === 'string' && data.match(/^(?:\w+:)?\/\/[^\s.]+\.\S/)) {
      return true; 
    }
    return false; 
  },
  errors: false,
});

    agreementReportURL: {
         type : ['string','null'],
         format:'uri',
         isNotEmpty:true,
         isAllowNullAndURI:true
    },
0
Jeremy Fiel On

This is much easier than a custom function

The assertion keyword minLength will only be enforced against a string value The annotation keyword format is not used for validation purposes unless you add the ajv-formats package.

I would also recommend upgrading to Ajv 8+ but be sure to pass the options object with {strict:false} if you want the Ajv to abide by the official JSON Schema specification, without {strict:false} the validator does not conform to the specification

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "agreementURL": {
       "type": ["string", "null"],
       "format": "uri",
       "minLength": 1
    }
  }
}