0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

0
Posted at

結論

それ用のオプションがあった -> 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を追加したときだけのように見えたため、気づくのが遅れました。

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

教訓

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?