JSON Schema: How to check if a field contains a value

Question:

I have a JSON schema validator where I need to check a specific field email to see if it’s one of 4 possible emails. Lets call the possibilities ['test1', 'test2', 'test3', 'test4']. Sometimes the emails contain a n new line separator so I need to account for that also. Is it possible to do a string contains method in JSON Schema?

Here is my schema without the email checks:

{
  "type": "object",
  "properties": {
    "data": {
        "type":"object",
        "properties": {
            "email": {
                "type": "string"
            }
        },
    "required": ["email"]
    }
  }
}

My input payload is:

{
  "data": {
      "email": "test3njunktext"
      }
}

I would need the following payload to pass validation since it has test3 in it. Thanks!

Asked By: staten12

||

Answers:

I can think of two ways:

Using enum you can define a list of valid emails:

{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {
        "email": {
          "enum": [
            "test1",
            "test2",
            "test3"
          ]
        }
      },
      "required": [
        "email"
      ]
    }
  }
}

Or with pattern which allows you to use a regular expression for matching a valid email:

{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {
        "email": {
          "pattern": "test"
        }
      },
      "required": [
        "email"
      ]
    }
  }
}
Answered By: customcommander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.