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

     1  package jsonschema
     2  
     3  import "fmt"
     4  
     5  // EvaluateMaxItems checks if the array data contains no more items than the maximum specified in the "maxItems" schema attribute.
     6  // According to the JSON Schema Draft 2020-12:
     7  //   - The value of "maxItems" must be a non-negative integer.
     8  //   - An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword.
     9  //   - If the data is not an array, the "maxItems" constraint does not apply and should be ignored.
    10  //
    11  // This method ensures that the array data instance conforms to the maximum items constraints defined in the schema.
    12  // If the instance violates this constraint, it returns a EvaluationError detailing the allowed maximum and the actual size.
    13  // If the data is not an array, it returns nil, indicating the data is valid for this constraint.
    14  //
    15  // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-maxitems
    16  func evaluateMaxItems(schema *Schema, array []interface{}) *EvaluationError {
    17  	if schema.MaxItems != nil {
    18  		if float64(len(array)) > *schema.MaxItems {
    19  			// If the array size exceeds the maximum allowed, construct and return an error.
    20  			return NewEvaluationError("maxItems", "items_too_long", "Value should have at most {max_items} items", map[string]interface{}{
    21  				"max_items": fmt.Sprintf("%.0f", *schema.MaxItems),
    22  				"count":     len(array),
    23  			})
    24  		}
    25  	}
    26  	return nil
    27  }