Help us understand the problem. What is going on with this article?

[validator.v9] pointerにFieldLevelの独自validateを設定したらnilの場合エラーになる

結論

それ用のオプションがあった -> omitempty

サンプルソース

example.go
// MyStruct ..
type MyStruct struct {
    String *string `validate:"omitempty,is-awesome"`
}

func main() {
    validate = validator.New()
    validate.RegisterValidation("is-awesome", ValidateMyVal)

    // ここでomitemptyを設定していない場合は、ValidateMyValが呼び出される前にエラーになる
    s := MyStruct{}
    err := validate.Struct(s)
    if err != nil {
        fmt.Printf("Err(s):\n%+v\n", err)
    }

    // omitemptyがなくても普通に動く
    str1 := "awesome"
    s.String = &str1
    err = validate.Struct(s)
    if err != nil {
        fmt.Printf("Err(s):\n%+v\n", err)
    }

    // omitemptyがなくても普通に動く
    str2 := "not awesome"
    s.String = &str2
    err = validate.Struct(s)
    if err != nil {
        fmt.Printf("Err(s):\n%+v\n", err)
    }
}

// ValidateMyVal implements validator.Func
func ValidateMyVal(fl validator.FieldLevel) bool {
    return fl.Field().String() == "awesome"
}

言い訳

問題が起きるのがRegisterValidationを使って、
独自のvalidationを追加したときだけのように見えたため、気づくのが遅れました。

もう少し影響のありそうなものを使っていれば早めに気づいたかも。

教訓

どうしてこれぐらいのことができないんだーと思ったら、
ソースを読もうとせずにドキュメントに一通り目を通すこと。。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away