tdegrunt / jsonschema

JSON Schema validation
Other
1.83k stars 262 forks source link

Pattern Regex are ignored #300

Closed ntregillus closed 4 years ago

ntregillus commented 4 years ago

https://github.com/tdegrunt/jsonschema/blob/b49eefa200ce0b8146f00ee8dc6153580573de19/examples/all.js#L59

I have been attempting to test a json schema's string property, but the Validator.Validate seems to ignore my type definitions "pattern" value entirely: https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.3.3

{
  "type: "object",
  "properties": {
    "singleField": {
      "type": "string",
      "pattern": /^$/
    }
  }
}

when I run this through validate

{
  "singleField": "thisShouldBeEmpty"
}

I am expecting an error, but the errors array of the result is empty. below is the code i would run:

var result = Validator.validate(testObj, schema);
console.log("results.errors should be 1, instead its", result.errors.length);
awwright commented 4 years ago

@ntregillus You should specify the regular expression as a string — the schema object should be compatible with a JSON Schema document parsed with JSON.parse.

Maybe as a future extension this should support a RegExp instance—or at the very least, it should error out if the value is an unexpected type.

ntregillus commented 4 years ago

I tried both as a regular expression, and a string wrapper (like below):

{
  "type": "object",
  "properties": {
    "singleField": {
      "type": "string",
      "pattern": "^$"
    }
  }
}

however it still does not work. I did notice though if my type was in an array definition, it was correctly validating my regex statement. It just appears the verification on an object property does not work.

awwright commented 4 years ago

@ntregillus Can you provide a minimal test case? I cannot reproduce this.

var schema = {
  "type": "object",
  "properties": {
    "singleField": {
      "type": "string",
      "pattern": "^$"
    }
  }
};
// returns: instance.singleField does not match pattern "^$"
console.log(jsonschema.validate({singleField:"x"}, schema).errors.toString());
awwright commented 4 years ago

I'm going to close this since this appears to have the correct behavior. Please try the latest release, 1.2.7, and open a new issue if you encounter any further problems.