github.com/kaptinlin/jsonschema@v0.4.6/pattern.go (about)

     1  package jsonschema
     2  
     3  import "regexp"
     4  
     5  // EvaluatePattern checks if the string data matches the regular expression specified in the "pattern" schema attribute.
     6  // According to the JSON Schema Draft 2020-12:
     7  //   - The value of "pattern" must be a string that should be a valid regular expression, according to the ECMA-262 regular expression dialect.
     8  //   - A string instance is considered valid if the regular expression matches the instance successfully.
     9  //     Note: Regular expressions are not implicitly anchored.
    10  //
    11  // This method ensures that the string data instance conforms to the pattern constraints defined in the schema.
    12  // If the instance does not match the pattern, it returns a EvaluationError detailing the expected pattern and the actual string.
    13  //
    14  // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-pattern
    15  func evaluatePattern(schema *Schema, instance string) *EvaluationError {
    16  	if schema.Pattern != nil {
    17  		// Gets a compiled regular expression, or compiles and caches it if not already present.
    18  		regExp, err := getCompiledPattern(schema)
    19  		if err != nil {
    20  			// Handle regular expression compilation errors.
    21  			return NewEvaluationError("pattern", "invalid_pattern", "Invalid regular expression pattern {pattern}", map[string]interface{}{
    22  				"pattern": *schema.Pattern,
    23  			})
    24  		}
    25  
    26  		// Check if the regular expression matches the string value.
    27  		if !regExp.MatchString(instance) {
    28  			// Data does not match the pattern.
    29  			return NewEvaluationError("pattern", "pattern_mismatch", "Value does not match the required pattern {pattern}", map[string]interface{}{
    30  				"pattern": *schema.Pattern,
    31  				"value":   instance,
    32  			})
    33  		}
    34  	}
    35  	return nil
    36  }
    37  
    38  func getCompiledPattern(schema *Schema) (*regexp.Regexp, error) {
    39  	if schema.compiledStringPattern == nil {
    40  		regExp, err := regexp.Compile(*schema.Pattern)
    41  		if err != nil {
    42  			return nil, err
    43  		}
    44  		schema.compiledStringPattern = regExp
    45  	}
    46  
    47  	return schema.compiledStringPattern, nil
    48  }