From 21deda8caa1807ec3d00d29ba41a407e6a5866d5 Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Mon, 27 Dec 2021 10:30:53 +0100 Subject: [PATCH] valid: add OptionalBool --- valid/valid.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/valid/valid.go b/valid/valid.go index 3de93e1353bd69f2ee22d410d1dc1f6613989402..dba77aeb4cb60f34e092c42eb41430945195c984 100644 --- a/valid/valid.go +++ b/valid/valid.go @@ -80,6 +80,34 @@ func (valid *Validation) OptionalString(name string, fn func(s string)) { } } +// Fetches a boolean from the validation context, which must have an input +// registered. If the field is not present, the callback is not run. If +// present, but not a boolean, an error is recorded. Otherwise, the function is +// called with the boolean for the user to conduct further validation with. +func (valid *Validation) OptionalBool(name string, fn func(b bool)) { + if valid.input == nil { + panic("Attempted to validate fields without input") + } + if o, ok := valid.input[name]; ok { + if o == nil { + return + } + var val bool + switch b := o.(type) { + case bool: + val = b + case *bool: + val = *b + default: + valid. + Error("Expected %s to be a bool", name). + WithField(name) + return + } + fn(val) + } +} + // Creates a validation error unconditionally. func (valid *Validation) Error(msg string, items ...interface{}) *ValidationError {