Explorar el Código

add validator to check if field value is one of a pre-defined list

Bozhin Zafirov hace 8 años
padre
commit
2ee7cabc8c
Se han modificado 1 ficheros con 18 adiciones y 0 borrados
  1. 18 0
      validators.go

+ 18 - 0
validators.go

@@ -50,6 +50,24 @@ func validLength(min, max int) ValidatorFunc {
 	}
 }
 
+// validFieldIn verifies if item is within the list of items
+func validFieldIn(list []string) ValidatorFunc {
+	var EInvalidValue = errors.New(
+		fmt.Sprintf(
+			"field value must be one of: %s",
+			strings.Join(list, ","),
+		),
+	)
+	return func(field FormField, ctx context.Context) error {
+		for _, item := range list {
+			if item == field.GetString() {
+				return nil
+			}
+		}
+		return EInvalidValue
+	}
+}
+
 // validInt returns error if field does not contain a valid integer value
 func validInt(field FormField, ctx context.Context) error {
 	_, err := field.GetInt()