[lxc-devel] [lxd/master] Validate: Adds Required() and makes Optional() accept multiple validators

tomponline on Github lxc-bot at linuxcontainers.org
Thu Aug 6 16:53:26 UTC 2020


A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 1300 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20200806/132a06c8/attachment.bin>
-------------- next part --------------
From 0f69cfdf8c20ba8e28836136aa156da77e2507fd Mon Sep 17 00:00:00 2001
From: Thomas Parrott <thomas.parrott at canonical.com>
Date: Thu, 6 Aug 2020 17:48:01 +0100
Subject: [PATCH] shared/validate: Adds Required() and makes Optional() accept
 multiple validators

Signed-off-by: Thomas Parrott <thomas.parrott at canonical.com>
---
 shared/validate/validate.go | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/shared/validate/validate.go b/shared/validate/validate.go
index cc1811d6ed..eaf6e52d9b 100644
--- a/shared/validate/validate.go
+++ b/shared/validate/validate.go
@@ -20,14 +20,28 @@ func stringInSlice(key string, list []string) bool {
 	return false
 }
 
-// Optional wraps a validator function to make it an optional field.
-func Optional(f func(value string) error) func(value string) error {
+// Required returns function that runs one or more validators, all must pass without error.
+func Required(validators ...func(value string) error) func(value string) error {
+	return func(value string) error {
+		for _, validator := range validators {
+			err := validator(value)
+			if err != nil {
+				return err
+			}
+		}
+
+		return nil
+	}
+}
+
+// Optional wraps Required() function to make it return nil if value is empty string.
+func Optional(validators ...func(value string) error) func(value string) error {
 	return func(value string) error {
 		if value == "" {
 			return nil
 		}
 
-		return f(value)
+		return Required(validators...)(value)
 	}
 }
 


More information about the lxc-devel mailing list