From d56e2d794b2ac6a36ab7a499c21345a08e58b2c0 Mon Sep 17 00:00:00 2001 From: Adnan Maolood Date: Wed, 26 Jan 2022 07:09:28 -0500 Subject: [PATCH] valid: Add NullableString Add a NullableString method to allow users to differentiate between the absence of a field and an explicitly provided null value. --- valid/valid.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/valid/valid.go b/valid/valid.go index 13466b80f22fbb583022e84e088ca50f1e0e358c..89f81e1299f550aaff8f748fdf1c9bb753af2b56 100644 --- a/valid/valid.go +++ b/valid/valid.go @@ -91,6 +91,34 @@ func (valid *Validation) OptionalString(name string, fn func(s string)) { } } +// Fetches a nullable string from the validation context, which must have an +// input registered. If the field is not present, the callback is not run. If +// present, but null, the function is called with null set to true. Otherwise, +// the function is called with the string for the user to conduct further +// validation with. +func (valid *Validation) NullableString(name string, fn func(s *string)) { + if valid.input == nil { + panic("Attempted to validate fields without input") + } + if o, ok := valid.input[name]; ok { + var val *string + if o != nil { + switch s := o.(type) { + case string: + val = &s + case *string: + val = s + default: + valid. + Error("Expected %s to be a string", name). + WithField(name) + return + } + } + fn(val) + } +} + // 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