LoginSignup
1
1

More than 5 years have passed since last update.

Golangで構造体に対して複数項目にまたがるバリデーションを定義する

Last updated at Posted at 2018-06-21

Golangのvalidator.v9を使って構造体に対する複数項目にまたがるバリデーションを定義するには、バリデータタグを定義するよりも RegisterStructValidation を使ったほうが簡単に書ける。

以下は ある特定の項目が真のとき他の項目に対してバリデーションを行う コードの例。

multiple_conditional_validator.go
package main

import (
    "fmt"
    "gopkg.in/go-playground/validator.v9"
)

type Person struct {
    IsMan  bool
    Age    int
    Height int
}

func main() {
    person := Person{
        IsMan:  true,
        Age:    10,
        Height: 0,
    }

    validate := validator.New()

    // personの構造体に対するバリデータを登録
    validate.RegisterStructValidation(multipleConditionalValidator, person)
    err := validate.Struct(person)

    if errorFields, ok := err.(validator.ValidationErrors); ok {
        for _, errorField := range errorFields {
            fmt.Printf("%s.%s\n", errorField.StructNamespace(), errorField.Tag())
        }
    }
}

func multipleConditionalValidator(sl validator.StructLevel) {
    args := sl.Current().Interface().(Person)

    // IsManが真のときのみ他のフィールドに対してバリデーションを継続して行う
    if args.IsMan {
        if args.Age < 1 {
            sl.ReportError(args.Age, "Person", "Age", "positive", "")
        }

        if args.Height < 1 {
            sl.ReportError(args.Age, "Person", "Height", "positive", "")
        }
    }
}
出力
$ go run multiple_conditional_validator.go
Person.Height.positive
1
1
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
1
1