From dc6db954edce9a9776f388d77098da46f1d9dbc8 Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Tue, 29 Jul 2025 13:45:36 +0200 Subject: [PATCH] fix(input/choice): add specific validation func --- CHANGELOG.md | 6 ++++++ form/field_choice.go | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2a2bf1..58de243 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ ## [Unreleased] +## v1.1.5 + +### Fixed + +- fix(input/choice): add specific validation func + ## v1.1.4 ### Fixed diff --git a/form/field_choice.go b/form/field_choice.go index 6a4014d..c74ae7a 100644 --- a/form/field_choice.go +++ b/form/field_choice.go @@ -19,6 +19,7 @@ import ( "reflect" "github.com/spf13/cast" + "gitnet.fr/deblan/go-form/validation" ) type Choice struct { @@ -124,6 +125,28 @@ func NewFieldChoice(name string) *Field { NewOption("empty_choice_label", "None"), ) + f.Validate = func(field *Field) bool { + isValid := FieldValidation(field) + + if len(validation.NewNotBlank().Validate(field.Data)) == 0 { + choices := field.GetOption("choices").Value.(*Choices) + isValidChoice := true + + for _, choice := range choices.GetChoices() { + if !choices.Match(field, choice.Value) { + isValidChoice = false + } + } + + if !isValidChoice { + field.Errors = append(field.Errors, validation.Error("This value is not valid.")) + isValid = false + } + } + + return isValid + } + f.WithBeforeBind(func(data any) (any, error) { choices := f.GetOption("choices").Value.(*Choices)