V2rson
V2rson

Reputation: 347

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

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",
   }
 }, 

Upvotes: 0

Views: 542

Answers (3)

Alon S
Alon S

Reputation: 195

Like this:

 "MyUrl": { "anyOf": [
     {"type": "string", "enum": [""]},
     {"type": "string", "format": "uri"}
 ]}

Upvotes: 0

Jeremy Fiel
Jeremy Fiel

Reputation: 3219

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
    }
  }
}

Upvotes: 0

V2rson
V2rson

Reputation: 347

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
    },

Upvotes: 0

Related Questions