skip to Main Content

i am having a url 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

Answers


  1. Chosen as BEST ANSWER

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

  2. 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
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search