fyne-io / fyne

Cross platform GUI toolkit in Go inspired by Material Design
https://fyne.io/
Other
25.14k stars 1.4k forks source link

Entry validation does not work for empty field (?) #2179

Closed JohannesHampel closed 3 years ago

JohannesHampel commented 3 years ago

Hi,

I'm using fyne 2.0.2, go 1.14 on macos. Sorry, if the question is studip, I am new to fyne and go:

I'd like to have an Entry where the entered value needs to have at least 2 characters. The validation works ok, if one inputs at least one character, but in case the Entry is left completely empty, no validation is done.

What I am doing wrong?

package main

import (
    "errors"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/layout"
    "fyne.io/fyne/v2/widget"
)

func main() {
    app := app.New()

    w := app.NewWindow("Hello")
    e := widget.NewEntry()
    e.Validator = func (str string) error {
        if len(e.Text)<2 {
            return errors.New("Too short")
        }
        return nil
    }

    content := container.New(layout.NewHBoxLayout(),  e)
    w.SetContent(content)

    w.ShowAndRun()
}
JohannesHampel commented 3 years ago

In the meanwhile I figured out that this behavior seems to be intended:

From entry_validation.go

func (r *validationStatusRenderer) Refresh() {
    r.entry.propertyLock.RLock()
    defer r.entry.propertyLock.RUnlock()
    if r.entry.Text == "" || r.entry.disabled {
        r.icon.Hide()
        return
    }
        ...

I guess this is the part where fyne comes to the conclusion that it never renders the validation icon in case the Entry is empty. So the question is: what is the best way to have an Entry that validates for required input?

andydotxyz commented 3 years ago

I think you may have found a bug. The intention is that we do not show errors for validation before the field is edited (i.e. when it's still blank) but that editing the field, then putting it back to blank, then moving focus elsewhere the error should appear.