The following pull request was submitted through Github. It can be accessed and reviewed at: https://github.com/lxc/lxd/pull/7738
This e-mail was sent by the LXC bot, direct replies will not reach the author unless they happen to be subscribed to this list. === Description (from pull-request) === This is an idea I had whilst working on the network name validation. Sometimes it would be useful to run multiple validators on a field, and right now the only choice we have is to create an anonymous function that calls multiple validators. This PR modifies the existing `Optional()` function to make it variadic so it can accept multiple validators. It also adds a `Required()` function which does the same as `Optional()` without the check that causes it to return nil if the supplied value is an empty string. This allows validation rules to be defined as follows: ```go rules := map[string]func(value string) error{ "parent": validate.Required(validInterfaceName, validate.IsURLSegmentSafe), "mtu": validate.Optional(validate.IsInt64), "vlan": validate.Optional(validate.IsNetworkVLAN, validate.IsInt64), } ``` This change is backwards compatible with current usage. Signed-off-by: Thomas Parrott <thomas.parr...@canonical.com>
From 0f69cfdf8c20ba8e28836136aa156da77e2507fd Mon Sep 17 00:00:00 2001 From: Thomas Parrott <thomas.parr...@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.parr...@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) } }
_______________________________________________ lxc-devel mailing list lxc-devel@lists.linuxcontainers.org http://lists.linuxcontainers.org/listinfo/lxc-devel