From 9e5365e0ec0c4005efc7a3cc47f67941840e4144 Mon Sep 17 00:00:00 2001 From: bashbunni <15822994+bashbunni@users.noreply.github.com> Date: Tue, 25 Mar 2025 06:51:14 -0700 Subject: [PATCH] docs: add example for ValidateFunc (#705) * docs(textinput): add ValidateFunc example * chore: remove print statement * chore: rename the -> this anonymous func --- textinput/textinput_test.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/textinput/textinput_test.go b/textinput/textinput_test.go index 6c288ab..162167e 100644 --- a/textinput/textinput_test.go +++ b/textinput/textinput_test.go @@ -1,6 +1,8 @@ package textinput import ( + "fmt" + "strconv" "strings" "testing" ) @@ -43,3 +45,36 @@ func Test_SlicingOutsideCap(t *testing.T) { textinput.Width = 32 textinput.View() } + +func ExampleValidateFunc() { + creditCardNumber := New() + creditCardNumber.Placeholder = "4505 **** **** 1234" + creditCardNumber.Focus() + creditCardNumber.CharLimit = 20 + creditCardNumber.Width = 30 + creditCardNumber.Prompt = "" + // This anonymous function is a valid function for ValidateFunc. + creditCardNumber.Validate = func(s string) error { + // Credit Card Number should a string less than 20 digits + // It should include 16 integers and 3 spaces + if len(s) > 16+3 { + return fmt.Errorf("CCN is too long") + } + + if len(s) == 0 || len(s)%5 != 0 && (s[len(s)-1] < '0' || s[len(s)-1] > '9') { + return fmt.Errorf("CCN is invalid") + } + + // The last digit should be a number unless it is a multiple of 4 in which + // case it should be a space + if len(s)%5 == 0 && s[len(s)-1] != ' ' { + return fmt.Errorf("CCN must separate groups with spaces") + } + + // The remaining digits should be integers + c := strings.ReplaceAll(s, " ", "") + _, err := strconv.ParseInt(c, 10, 64) + + return err + } +}