github.com/ns1/terraform@v0.7.10-0.20161109153551-8949419bef40/helper/validation/validation.go (about)

     1  package validation
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/hashicorp/terraform/helper/schema"
     8  )
     9  
    10  // IntBetween returns a SchemaValidateFunc which tests if the provided value
    11  // is of type int and is between min and max (inclusive)
    12  func IntBetween(min, max int) schema.SchemaValidateFunc {
    13  	return func(i interface{}, k string) (s []string, es []error) {
    14  		v, ok := i.(int)
    15  		if !ok {
    16  			es = append(es, fmt.Errorf("expected type of %s to be int", k))
    17  			return
    18  		}
    19  
    20  		if v < min || v > max {
    21  			es = append(es, fmt.Errorf("expected %s to be in the range (%d - %d), got %d", k, min, max, v))
    22  			return
    23  		}
    24  
    25  		return
    26  	}
    27  }
    28  
    29  // StringInSlice returns a SchemaValidateFunc which tests if the provided value
    30  // is of type string and matches the value of an element in the valid slice
    31  // will test with in lower case if ignoreCase is true
    32  func StringInSlice(valid []string, ignoreCase bool) schema.SchemaValidateFunc {
    33  	return func(i interface{}, k string) (s []string, es []error) {
    34  		v, ok := i.(string)
    35  		if !ok {
    36  			es = append(es, fmt.Errorf("expected type of %s to be string", k))
    37  			return
    38  		}
    39  
    40  		for _, str := range valid {
    41  			if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) {
    42  				return
    43  			}
    44  		}
    45  
    46  		es = append(es, fmt.Errorf("expected %s to be one of %v, got %s", k, valid, v))
    47  		return
    48  	}
    49  }