github.com/kaptinlin/jsonschema@v0.4.6/maxlength.go (about) 1 package jsonschema 2 3 import ( 4 "fmt" 5 "unicode/utf8" 6 ) 7 8 // EvaluateMaxLength checks if the length of a string instance does not exceed the maxLength specified in the schema. 9 // According to the JSON Schema Draft 2020-12: 10 // - The "maxLength" keyword must be a non-negative integer. 11 // - A string instance is valid against this keyword if its length is less than or equal to the value of this keyword. 12 // - The length of a string instance is defined as the number of its characters as defined by RFC 8259. 13 // 14 // This method ensures that the string data instance does not exceed the maximum length defined in the schema. 15 // If the instance exceeds this length, it returns a EvaluationError detailing the maximum allowed length and the actual length. 16 // 17 // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-maxlength 18 func evaluateMaxLength(schema *Schema, value string) *EvaluationError { 19 if schema.MaxLength != nil { 20 // Use utf8.RuneCountInString to correctly count the number of graphemes in the string 21 length := utf8.RuneCountInString(value) 22 if length > int(*schema.MaxLength) { 23 // String exceeds the maximum length. 24 return NewEvaluationError("maxLength", "string_too_long", "Value should be at most {max_length} characters", map[string]interface{}{ 25 "max_length": fmt.Sprintf("%.0f", *schema.MaxLength), 26 "length": length, 27 }) 28 } 29 } 30 return nil 31 }