How to call function on lost focus in Fyne

Viewed 64

I just started learning Go coming from JS/TS. I want to validate an entry in fyne on loss of focus.

I got it to work like this :

type dateEntry struct {
    widget.Entry
}

func NewDateEntry() *dateEntry {
    entry := &dateEntry{}
    entry.ExtendBaseWidget(entry)
    return entry
}

func (e *dateEntry) FocusLost() {
    println("Focus lost")
    e.Validate()
}

func main() {
    dateInput := NewDateEntry()
    dateInput.SetPlaceHolder("DD/MM/YYYY")
    dateInput.Validator = func(s string) (err error) {
        reDate := regexp.MustCompile("(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)")
        if s == "" {
            return fmt.Errorf("date required")
        } else if !reDate.MatchString(s) {
            return fmt.Errorf("date invalid")
        }
        return nil
    }
    w.SetContent(dateInput)
    w.ShowAndRun()
}

There seems to be a lot of code just to trigger a function on loss of focus. Is there a simpler way to do this?

Now the blue line at the bottom of the input is no longer displayed anymore when focus is gained, how can I keep the style when focus is gained while handling a focus loss event?

1 Answers

To trigger the function you could extend Entry and override OnFocusLost (Because Entry already handles this). However for validation it is better to use the Validator api as that provides visual feedback for your user automatically.

I’m not sure about the statement that your example is a lot of code - each line seems to be conveying meaning.

Related