简体   繁体   中英

How to call function on lost focus in Fyne

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM