github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/validator/maxlength/maxlength.go (about)

     1  // Copyright (c) 2018-2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package maxlength
     6  
     7  import (
     8  	"fmt"
     9  	"reflect"
    10  	"regexp"
    11  	"strconv"
    12  )
    13  
    14  // ValidateString validates that input is not longer than max
    15  func ValidateString(input string, max int) (bool, error) {
    16  	if len(input) > max {
    17  		return false, fmt.Errorf("%d characters, max allowed %d", len(input), max)
    18  	}
    19  
    20  	return true, nil
    21  }
    22  
    23  // ValidateStructField validates value based on the tag in the form maxlength=10
    24  func ValidateStructField(value reflect.Value, tag string) (bool, error) {
    25  	re := regexp.MustCompile(`^maxlength=(\d+)$`)
    26  	parts := re.FindStringSubmatch(tag)
    27  
    28  	if len(parts) != 2 {
    29  		return false, fmt.Errorf("invalid tag '%s', must be maxlength=n", tag)
    30  	}
    31  
    32  	max, _ := strconv.Atoi(parts[1])
    33  
    34  	switch value.Kind() {
    35  	case reflect.String:
    36  		return ValidateString(value.String(), max)
    37  	case reflect.Slice:
    38  		l := value.Slice(0, value.Len()).Len()
    39  		if l > max {
    40  			return false, fmt.Errorf("%d values, max allowed %d", l, max)
    41  		}
    42  
    43  		return true, nil
    44  
    45  	default:
    46  		return false, fmt.Errorf("cannot check length of %s type", value.Kind().String())
    47  	}
    48  }