Open1

【Go】バリデーションライブラリの比較

雑雑雑雑

go-playground/validator

  • structにタグを指定してバリデーションできる
  • 複数のバリデーションエラーを検知・出力できる

https://go.dev/play/p/KptmgPtAAHQ

package main

import (
	"fmt"

	"github.com/go-playground/validator/v10"
)

type Request struct {
	Name string `validate:"required"`
	Age  int    `validate:"required,gt=0"`
}

func main() {
	validate := validator.New()
	fmt.Println(validate.Struct(Request{
		Age: -100,
	}))
}
Key: 'Request.Name' Error:Field validation for 'Name' failed on the 'required' tag
Key: 'Request.Age' Error:Field validation for 'Age' failed on the 'gt' tag