1
{
  $jsonSchema: {
    bsonType: "object",
    required: ["firstName", "lastName", "email", "destination"],
    properties: {
      firstName: {
        bsonType: "string",
        description: "First name is required!"
      },
      lastName: {
        bsonType: "string",
        description: "Last name is required!"
      },
      email: {
        bsonType: "string",
        pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$",
        description: "Email is required"
      },
      destination: {
        bsonType: "string",
        description: "Destination is require!"
      }
    }
  }
}

In the above $jsonSchema, I attempt to use pattern as part of the schema specification

However, me existing ✉️ data fails validation inside of Compass.

This same pattern works just fine on client-side ReactJS form validation, so IK that the pattern itself is good.

However, something must be amiss with how we use this in $jsonSchema.

CodeFinity
  • 1,142
  • 2
  • 19
  • 19
  • What data failed validation? – D. SM Aug 26 '20 at 06:01
  • 1
    Also, your email regular expression is bogus. There are all kinds of TLDs out there with more than 4 characters, like .museum. – D. SM Aug 26 '20 at 06:03
  • Properly validating an email via regular expression is hard: https://stackoverflow.com/a/201378/89211 - You have to decide what level of regular expression validation you're happy with. – Relequestual Aug 26 '20 at 07:22
  • Please provide example data you're validating which fails. – Relequestual Aug 26 '20 at 07:23
  • Mongodb uses PCRE regular expression, but it looks like your regex is simple enough not to cause a problem there. – Relequestual Aug 26 '20 at 07:26
  • I've noted your regular expression only accounts for upper case and not lower case. You can't set regex flags with JSON Schema (for example to ignore case) – Relequestual Aug 26 '20 at 07:27

1 Answers1

0

JSON Schema is encoded in JSON, and as such, strings need to be escaped. This includes \ which must become \\, so where in your regex you have \., you need to escape it to become \\..

Having said that, as I don't have examples of your JSON data (and the email) you're trying to valid, I'm assuming what you've said is correct regarding the regular expression being sufficient for you elsewhere.

Relequestual
  • 11,631
  • 6
  • 47
  • 83