github.com/kaptinlin/jsonschema@v0.4.6/minlength.go (about) 1 package jsonschema 2 3 import ( 4 "unicode/utf8" 5 ) 6 7 // EvaluateMinLength checks if the length of a string instance meets or exceeds the minLength specified in the schema. 8 // According to the JSON Schema Draft 2020-12: 9 // - The "minLength" keyword must be a non-negative integer. 10 // - A string instance is valid against this keyword if its length is greater than or equal to the value of this keyword. 11 // - The length of a string instance is defined as the number of its characters as defined by RFC 8259. 12 // - Omitting this keyword has the same behavior as a value of 0. 13 // 14 // This method ensures that the string data instance does not fall short of the minimum length defined in the schema. 15 // If the instance is shorter than this length, it returns a EvaluationError detailing the minimum required length and the actual length. 16 // 17 // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-minlength 18 func evaluateMinLength(schema *Schema, value string) *EvaluationError { 19 if schema.MinLength != 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.MinLength) { 23 // String does not meet the minimum length. 24 return NewEvaluationError("minLength", "string_too_short", "Value should be at least {min_length} characters", map[string]interface{}{ 25 "min_length": *schema.MinLength, 26 "length": length, 27 }) 28 } 29 } 30 return nil 31 }