From b4f00220f903837537313063b6fb7cf3e51eeca7 Mon Sep 17 00:00:00 2001 From: Yousong Zhou Date: Mon, 10 Sep 2018 16:01:32 +0000 Subject: [PATCH] validators: add ValidatorStringMultiChoices --- pkg/cloudcommon/validators/validators.go | 87 ++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/pkg/cloudcommon/validators/validators.go b/pkg/cloudcommon/validators/validators.go index 305beb3a2c..58e1463342 100644 --- a/pkg/cloudcommon/validators/validators.go +++ b/pkg/cloudcommon/validators/validators.go @@ -11,6 +11,7 @@ import ( "net" "reflect" "regexp" + "strings" "yunion.io/x/jsonutils" "yunion.io/x/onecloud/pkg/cloudcommon/db" @@ -141,6 +142,92 @@ func (v *ValidatorStringChoices) Validate(data *jsonutils.JSONDict) error { return nil } +type ValidatorStringMultiChoices struct { + Validator + Choices Choices + defaultVal string + Value string + sep string + keepDup bool +} + +func NewStringMultiChoicesValidator(key string, choices Choices) *ValidatorStringMultiChoices { + v := &ValidatorStringMultiChoices{ + Validator: Validator{Key: key}, + Choices: choices, + } + v.parent = v + return v +} + +func (v *ValidatorStringMultiChoices) Sep(s string) *ValidatorStringMultiChoices { + v.sep = s + return v +} + +func (v *ValidatorStringMultiChoices) KeepDup(b bool) *ValidatorStringMultiChoices { + v.keepDup = b + return v +} + +func (v *ValidatorStringMultiChoices) validateString(s string) (string, bool) { + choices := strings.Split(s, v.sep) + j := 0 + for i, choice := range choices { + if !v.Choices.Has(choice) { + return "", false + } + if !v.keepDup { + isDup := false + for k := 0; k < j; k++ { + if choices[k] == choices[i] { + isDup = true + } + } + if !isDup { + choices[j] = choices[i] + j += 1 + } + } + } + if !v.keepDup { + choices = choices[:j] + } + s = strings.Join(choices, v.sep) + return s, true +} + +func (v *ValidatorStringMultiChoices) Default(s string) IValidator { + s, ok := v.validateString(s) + if !ok { + panic("invalid default for " + v.Key) + } + v.Validator.Default(s) + return v +} + +func (v *ValidatorStringMultiChoices) getValue() interface{} { + return v.Value +} + +func (v *ValidatorStringMultiChoices) Validate(data *jsonutils.JSONDict) error { + if err, isSet := v.Validator.validateEx(data); err != nil || !isSet { + return err + } + s, err := v.value.GetString() + if err != nil { + return newGeneralError(v.Key, err) + } + s, ok := v.validateString(s) + if !ok { + return newInvalidChoiceError(v.Key, v.Choices, s) + } + // in case it's stringified from v.value + data.Set(v.Key, jsonutils.NewString(s)) + v.Value = s + return nil +} + type ValidatorRange struct { Validator Lower int64