douji6461 2016-01-23 18:35
浏览 19
已采纳

为什么我的struct方法总是返回false?

I'm trying to do validation on my form struct in a method that returns a bool, but I keep getting false even when it should be returning true..

If you look towards the end of the Validate method, you'll see I write validated := len(this.Errors) == 0 which should be making "validated" either true or false based on whether the Errors map has items or not, and then I return validated.

When I fill out my form accurately, there should be no errors yet I still get false when I should be getting true.

Can someone explain? Is this not how Go works?

form.go:

package models

import (
    "../config"
    "../util"
)

type Form struct {
    Name    string
    Email   string
    Phone   string
    Message string
    Thanks  string
    ErrorHandler
}

func (this *Form) Validate() bool {
    this.Errors = make(map[string]string)

    matched := util.MatchRegexp(".+@.+\\..+", this.Email)

    if !util.IsEmpty(this.Email) {
        if matched == false {
            this.Errors["Email"] = config.EMAIL_INVALID
        }
    } else {
        this.Errors["Email"] = config.EMAIL_EMPTY
    }

    if util.IsEmpty(this.Name) {
        this.Errors["Name"] = config.NAME_EMPTY
    }

    if util.IsEmpty(this.Phone) {
        this.Errors["Phone"] = config.PHONE_EMPTY
    }

    if util.IsEmpty(this.Message) {
        this.Errors["Message"] = config.MESSAGE_EMPTY
    }

    validated := len(this.Errors) == 0

    if validated {
        this.Thanks = config.THANK_YOU
    }

    return validated
}

errorhandler.go:

package models

type ErrorHandler struct {
    Errors map[string]string
}

func (this *ErrorHandler) HandleErr(err string) {
    this.Errors = make(map[string]string)
    this.Errors["Error"] = err
}

And this is where I try to call the Validate method -- in a function in my controller:

form := &models.Form{
    Name:    r.FormValue("name"),
    Email:   r.FormValue("email"),
    Phone:   r.FormValue("phone"),
    Message: r.FormValue("message")}

if form.Validate() {
    // This never runs because 'form.Validate()' is always false
}

I don't think the util.IsEmpty() is the culprit here.. just checks if the string is empty:

func IsEmpty(str string) bool {
    return strings.TrimSpace(str) == ""
}

Any help would be appreciated!

  • 写回答

1条回答 默认 最新

  • dping1968 2016-01-23 19:22
    关注

    It's best to debug this kind of problem with a log statement like:

    log.Printf("form: %v", form)

    before calling validate, so it's clear what the input data looks like.

    Greetings, Philip

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分