eclipsesource/play-json-schema-validator

How do i use pattern?

Closed this issue · 4 comments

First of all thanks for providing the validator ... very helpful especially beginners in scala like me ..

Question: How do i use patterns? I have the input and schema as shown below which doesnt work.

{
    "id": "398402",
    "start": "2016-01-04T18:31:00Z"
}

 val schema = Json.fromJson[SchemaType](Json.parse(
    """{
      |"properties": {
      |  "id":    { "type": "string" },
      |  "spoolStart":  { "type": "string",
      |                         "pattern": "^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z"
      |                       }
      |}
    }""".stripMargin)).get

Hi,
the problem is that \d in this context is an invalid escape character, so the JSON parser will complain about it.
If you have a look at spec, the preferred way to specify a character class is via brackets, so for your example this should work:

 val schema = Json.fromJson[SchemaType](Json.parse(
        """{
          |  "properties": {
          |    "id":    { "type": "string" },
          |    "spoolStart":  {
          |      "type": "string",
          |      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"
          |    }
          |  }
          |}""".stripMargin)).get

Alternatively you could also double escape the character class like in \\d, which is also ought to work. Besides that, I noticed that you pass a JSON instance with a property named start, which perhaps should be named spoolStart.

Hello,

I tried this pattern too "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z but felt its too long and not very easy to read.

So wanted to ask you if there is any other way.

Yes you're right ... the JSON field name should be spoolStart

If i have any questions like this, is there a document/file which i can use for reference?

I found this guide to be a very good intro to JSON Schema.
Regarding readabilty: I think for your use-case you could stick to the format keyword with the format being set to date-time, but the validator currently does not yet support formats. I've created issue #24 to track this.