docs: add isbn form validation example (#1401)

Co-authored-by: Andrey Nering <andreynering@users.noreply.github.com>
This commit is contained in:
Mattis 2025-05-12 19:20:41 +02:00 committed by GitHub
parent 6d9c955952
commit f502dc548b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 272 additions and 214 deletions

View file

@ -27,13 +27,13 @@ and timer) together in a single application and switch between them.
<img width="750" src="./composable-views/composable-views.gif" />
</a>
### Credit Card Form
### ISBN Book Form
The `credit-card-form` example demonstrates how to build a multi-step form with
`textinputs` bubbles and validation on the inputs.
The `isbn-form` example demonstrates how to build a multi-step form with
`textinput` bubbles and validation on the inputs.
<a href="./credit-card-form/main.go">
<img width="750" src="./credit-card-form/credit-card-form.gif" />
<a href="./isbn-form/main.go">
<img width="750" src="./isbn-form/isbn-form.gif" />
</a>
### Debounce

View file

@ -1,3 +0,0 @@
# Credit Card Form
<img width="800" src="./credit-card-form.gif" />

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

View file

@ -1,203 +0,0 @@
package main
import (
"fmt"
"log"
"strconv"
"strings"
"github.com/charmbracelet/bubbles/v2/textinput"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/charmbracelet/lipgloss/v2"
)
func main() {
p := tea.NewProgram(initialModel())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
}
type (
errMsg error
)
const (
ccn = iota
exp
cvv
)
var (
hotPink = lipgloss.Color("#FF06B7")
darkGray = lipgloss.Color("#767676")
inputStyle = lipgloss.NewStyle().Foreground(hotPink)
continueStyle = lipgloss.NewStyle().Foreground(darkGray)
)
type model struct {
inputs []textinput.Model
focused int
err error
}
// Validator functions to ensure valid input
func ccnValidator(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
}
func expValidator(s string) error {
// The 3 character should be a slash (/)
// The rest should be numbers
e := strings.ReplaceAll(s, "/", "")
_, err := strconv.ParseInt(e, 10, 64)
if err != nil {
return fmt.Errorf("EXP is invalid")
}
// There should be only one slash and it should be in the 2nd index (3rd character)
if len(s) >= 3 && (strings.Index(s, "/") != 2 || strings.LastIndex(s, "/") != 2) {
return fmt.Errorf("EXP is invalid")
}
return nil
}
func cvvValidator(s string) error {
// The CVV should be a number of 3 digits
// Since the input will already ensure that the CVV is a string of length 3,
// All we need to do is check that it is a number
_, err := strconv.ParseInt(s, 10, 64)
return err
}
func initialModel() model {
var inputs []textinput.Model = make([]textinput.Model, 3)
inputs[ccn] = textinput.New()
inputs[ccn].Placeholder = "4505 **** **** 1234"
inputs[ccn].Focus()
inputs[ccn].CharLimit = 20
inputs[ccn].SetWidth(30)
inputs[ccn].Prompt = ""
inputs[ccn].Validate = ccnValidator
inputs[ccn].VirtualCursor = true
inputs[exp] = textinput.New()
inputs[exp].Placeholder = "MM/YY "
inputs[exp].CharLimit = 5
inputs[exp].SetWidth(5)
inputs[exp].Prompt = ""
inputs[exp].Validate = expValidator
inputs[exp].VirtualCursor = true
inputs[cvv] = textinput.New()
inputs[cvv].Placeholder = "XXX"
inputs[cvv].CharLimit = 3
inputs[cvv].SetWidth(5)
inputs[cvv].Prompt = ""
inputs[cvv].Validate = cvvValidator
inputs[cvv].VirtualCursor = true
return model{
inputs: inputs,
focused: 0,
err: nil,
}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds := make([]tea.Cmd, len(m.inputs))
switch msg := msg.(type) {
case tea.KeyPressMsg:
switch msg.String() {
case "enter":
if m.focused == len(m.inputs)-1 {
return m, tea.Quit
}
m.nextInput()
case "ctrl+c", "esc":
return m, tea.Quit
case "shift+tab", "ctrl+p":
m.prevInput()
case "tab", "ctrl+n":
m.nextInput()
}
for i := range m.inputs {
m.inputs[i].Blur()
}
m.inputs[m.focused].Focus()
// We handle errors just like any other message
case errMsg:
m.err = msg
return m, nil
}
for i := range m.inputs {
m.inputs[i], cmds[i] = m.inputs[i].Update(msg)
}
return m, tea.Batch(cmds...)
}
func (m model) View() string {
return fmt.Sprintf(
` Total: $21.50:
%s
%s
%s %s
%s %s
%s
`,
inputStyle.Width(30).Render("Card Number"),
m.inputs[ccn].View(),
inputStyle.Width(6).Render("EXP"),
inputStyle.Width(6).Render("CVV"),
m.inputs[exp].View(),
m.inputs[cvv].View(),
continueStyle.Render("Continue ->"),
) + "\n"
}
// nextInput focuses the next input field
func (m *model) nextInput() {
m.focused = (m.focused + 1) % len(m.inputs)
}
// prevInput focuses the previous input field
func (m *model) prevInput() {
m.focused--
// Wrap around
if m.focused < 0 {
m.focused = len(m.inputs) - 1
}
}

View file

@ -10,8 +10,9 @@ require (
github.com/charmbracelet/colorprofile v0.3.1
github.com/charmbracelet/glamour/v2 v2.0.0-20250423201235-510d0f0fc9a8
github.com/charmbracelet/harmonica v0.2.0
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1.0.20250423194624-2790cd0292d3
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta1
github.com/charmbracelet/x/ansi v0.9.2
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250512102446-03000fe596cb
github.com/charmbracelet/x/exp/teatest/v2 v2.0.0-20250324105510-c72bdbf70572
github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776
github.com/lucasb-eyer/go-colorful v1.2.0

View file

@ -20,12 +20,14 @@ github.com/charmbracelet/glamour/v2 v2.0.0-20250423201235-510d0f0fc9a8 h1:HZI97g
github.com/charmbracelet/glamour/v2 v2.0.0-20250423201235-510d0f0fc9a8/go.mod h1:iemPeLZyCdU8rMYAxNWDg1g+pVVKCIc/mq8h+Dg5BLk=
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1.0.20250423194624-2790cd0292d3 h1:TOsAJnG36R/wTKMf8HaWxKys16oOqVdywVLct1Ek8CU=
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1.0.20250423194624-2790cd0292d3/go.mod h1:tRlx/Hu0lo/j9viunCN2H+Ze6JrmdjQlXUQvvArgaOc=
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta1 h1:SOylT6+BQzPHEjn15TIzawBPVD0QmhKXbcb3jY0ZIKU=
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta1/go.mod h1:tRlx/Hu0lo/j9viunCN2H+Ze6JrmdjQlXUQvvArgaOc=
github.com/charmbracelet/x/ansi v0.9.2 h1:92AGsQmNTRMzuzHEYfCdjQeUzTrgE1vfO5/7fEVoXdY=
github.com/charmbracelet/x/ansi v0.9.2/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
github.com/charmbracelet/x/cellbuf v0.0.14-0.20250505150409-97991a1f17d1 h1:MTSs/nsZNfZPbYk/r9hluK2BtwoqvEYruAujNVwgDv0=
github.com/charmbracelet/x/cellbuf v0.0.14-0.20250505150409-97991a1f17d1/go.mod h1:xBlh2Yi3DL3zy/2n15kITpg0YZardf/aa/hgUaIM6Rk=
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250512102446-03000fe596cb h1:zWZuMwdWAYWKUwIq5lM2FWn/itBHnTNM8Q5m23ob6Og=
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250512102446-03000fe596cb/go.mod h1:yCm2RAfDJBOj+SRq8m3R2sNxrEAaS5HuCx/JzJr9YsY=
github.com/charmbracelet/x/exp/golden v0.0.0-20250207160936-21c02780d27a h1:FsHEJ52OC4VuTzU8t+n5frMjLvpYWEznSr/u8tnkCYw=
github.com/charmbracelet/x/exp/golden v0.0.0-20250207160936-21c02780d27a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI=

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

View file

@ -0,0 +1,16 @@
Type "go run ./isbn-form"
Enter
Sleep 2s
Type "9783548372570"
Sleep 500ms
Sleep 1s
Down
Sleep 500ms
Type "my book title"
Sleep 500ms
Backspace 10
Type "title"
Sleep 500ms
Enter
Sleep 3s
Output isbn-form.gif

245
examples/isbn-form/main.go Normal file
View file

@ -0,0 +1,245 @@
package main
import (
"fmt"
"log"
"strings"
"unicode"
"github.com/charmbracelet/bubbles/v2/textinput"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/charmbracelet/lipgloss/v2"
"github.com/charmbracelet/x/exp/charmtone"
)
func main() {
p := tea.NewProgram(initialModel())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
}
type (
errMsg error
)
var (
inputStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Tang.Hex()))
continueStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Anchovy.Hex()))
validStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Guac.Hex()))
errStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(charmtone.Cherry.Hex()))
)
type model struct {
isbnInput textinput.Model
titleInput textinput.Model
focusedInput int
err error
}
// canFindBook returns whether the find button is to be pressed
func (m model) canFindBook() bool {
correctIsbnGiven := m.isbnInput.Err == nil && len(m.isbnInput.Value()) != 0
correctTitleGiven := m.titleInput.Err == nil && len(m.titleInput.Value()) != 0
return correctIsbnGiven && correctTitleGiven
}
// Validator function to ensure valid input
func isbn13Validator(s string) error {
// A valid ISBN looks like this:
// 978-3-548-37257-0 or
// 9783548372570 without any spaces
// Remove dashes
s = strings.ReplaceAll(s, "-", "")
if len(s) != 13 {
return fmt.Errorf("ISBN is of wrong length")
}
for _, c := range s {
if !unicode.IsDigit(c) {
return fmt.Errorf("ISBN contains invalid characters")
}
}
gs1Prefix := s[:3]
switch gs1Prefix {
case "978", "979":
break
default:
return fmt.Errorf("ISBN has invalid GS1 prefix")
}
// The last digit, the check digit,
// must make the checksum a multiple of 10.
// All digits are added up after being multiplied
// by either 1 or 3 alternately.
// So 9x1 + 7x3 + 8x1 + ... + 0 must be a multiple of 10.
sum := 0
for i, c := range s {
// Convert rune to int
n := int(c - '0')
// Multiply the uneven indices by 3
if i%2 != 0 {
n *= 3
}
sum += n
}
if sum%10 != 0 {
return fmt.Errorf("ISBN has invalid check digit")
}
return nil
}
var bannedTitleWords = []string{
"very",
"bad",
"words",
"that",
"should",
"not",
"appear",
"in",
"book",
"titles",
}
func bookTitleValidator(s string) error {
s = strings.TrimSpace(s)
if len(s) == 0 {
return fmt.Errorf("Book title is empty")
}
for _, bannedWord := range bannedTitleWords {
if strings.Contains(s, bannedWord) {
return fmt.Errorf("Book title contains banned word %q", bannedWord)
}
}
return nil
}
func initialModel() model {
isbnInput := textinput.New()
isbnInput.Focus()
isbnInput.Placeholder = "978-X-XXX-XXXXX-X"
isbnInput.CharLimit = 17
isbnInput.SetWidth(30)
isbnInput.Prompt = ""
isbnInput.Validate = isbn13Validator
titleInput := textinput.New()
titleInput.Blur()
titleInput.Placeholder = "Title"
titleInput.CharLimit = 100
titleInput.SetWidth(100)
titleInput.Prompt = ""
titleInput.Validate = bookTitleValidator
return model{
isbnInput: isbnInput,
titleInput: titleInput,
focusedInput: 0,
err: nil,
}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyPressMsg:
switch msg.String() {
case "up", "down":
// Switch between text inputs
switch m.focusedInput {
case 0:
m.focusedInput = 1
m.titleInput.Focus()
m.isbnInput.Blur()
case 1:
m.focusedInput = 0
m.isbnInput.Focus()
m.titleInput.Blur()
}
case "enter":
// Enter is blocked until all inputs are ok
if m.canFindBook() {
return m, tea.Quit
}
case "ctrl+c", "esc":
return m, tea.Quit
}
// We handle errors just like any other message
case errMsg:
m.err = msg
return m, nil
}
var isbnCommand tea.Cmd
m.isbnInput, isbnCommand = m.isbnInput.Update(msg)
var titleCommand tea.Cmd
m.titleInput, titleCommand = m.titleInput.Update(msg)
return m, tea.Batch(isbnCommand, titleCommand)
}
func (m model) View() string {
var continueText string
if m.canFindBook() {
continueText = continueStyle.Render("Find ->")
}
var isbnErrorText string
if m.isbnInput.Value() != "" {
if m.isbnInput.Err != nil {
isbnErrorText = errStyle.Render(m.isbnInput.Err.Error())
} else {
isbnErrorText = validStyle.Render("Valid ISBN")
}
}
var titleErrorText string
if m.titleInput.Value() != "" {
if m.titleInput.Err != nil {
titleErrorText = errStyle.Render(m.titleInput.Err.Error())
} else {
titleErrorText = validStyle.Render("Valid title")
}
}
return fmt.Sprintf(
` Search book:
%s
%s
%s
%s
%s
%s
%s
`,
inputStyle.Width(30).Render("ISBN"),
m.isbnInput.View(),
isbnErrorText,
inputStyle.Width(30).Render("Title"),
m.titleInput.View(),
titleErrorText,
continueText,
) + "\n"
}