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

     1  // Copyright (c) 2020-2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package regex
     6  
     7  import (
     8  	"fmt"
     9  	"reflect"
    10  	"regexp"
    11  )
    12  
    13  // ValidateString validates that a string matches a regex
    14  func ValidateString(input string, regex string) (bool, error) {
    15  	re, err := regexp.Compile(regex)
    16  	if err != nil {
    17  		return false, fmt.Errorf("invalid regex '%s'", regex)
    18  	}
    19  
    20  	if !re.MatchString(input) {
    21  		return false, fmt.Errorf("input does not match '%s'", regex)
    22  	}
    23  
    24  	return true, nil
    25  }
    26  
    27  // ValidateStructField validates that field holds a string matching the regex
    28  // tag must be in the form `validate:"regex=\d+"`
    29  func ValidateStructField(value reflect.Value, tag string) (bool, error) {
    30  	re := regexp.MustCompile(`^regex=(.+)$`)
    31  	parts := re.FindStringSubmatch(tag)
    32  
    33  	if len(parts) != 2 {
    34  		return false, fmt.Errorf("invalid tag '%s', must be in the form regex=^hello.+world$", tag)
    35  	}
    36  
    37  	if value.Kind() != reflect.String {
    38  		return false, fmt.Errorf("only strings can be regex validated")
    39  	}
    40  
    41  	return ValidateString(value.String(), parts[1])
    42  }