validator

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package validator validates structs using go-playground/validator with JSON field names.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorsToString

func ErrorsToString(errs []*ErrorResponse) string

ErrorsToString converts a slice of ErrorResponse to a single string.

func Register

func Register(tag string, fn Func) error

Register adds a custom validation rule to the default validator.

Register is NOT thread-safe and must be called during application startup, before any concurrent calls to ValidateStruct.

Types

type ErrorResponse

type ErrorResponse struct {
	Field string `json:"field"`
	Tag   string `json:"tag"`
	Param string `json:"param,omitempty"`
	Value string `json:"value,omitempty"`
}

ErrorResponse represents a single validation error.

func ValidateStruct

func ValidateStruct(payload any) []*ErrorResponse

ValidateStruct validates a struct and returns a slice of ErrorResponse. If payload is nil or not a struct, it returns a single ErrorResponse with Tag "invalid" rather than panicking.

Example

ValidateStruct checks `validate` struct tags and returns one ErrorResponse per failing field. Field names come from the `json` tag.

package main

import (
	"fmt"

	"github.com/rahmadafandi/fibr/validator"
)

func main() {
	type SignupInput struct {
		Email    string `json:"email" validate:"required,email"`
		Password string `json:"password" validate:"required,min=8"`
	}

	errs := validator.ValidateStruct(SignupInput{Email: "not-an-email", Password: "short"})
	for _, e := range errs {
		fmt.Printf("%s failed %q\n", e.Field, e.Tag)
	}
}
Output:
email failed "email"
password failed "min"
Example (Valid)

A valid struct returns no errors.

package main

import (
	"fmt"

	"github.com/rahmadafandi/fibr/validator"
)

func main() {
	type SignupInput struct {
		Email string `json:"email" validate:"required,email"`
	}

	errs := validator.ValidateStruct(SignupInput{Email: "user@example.com"})
	fmt.Println("errors:", len(errs))
}
Output:
errors: 0

type FieldLevel

type FieldLevel = govalidator.FieldLevel

FieldLevel is re-exported so callers can write custom rules without importing the underlying validator library directly.

type Func

type Func = govalidator.Func

Func is the signature for custom validation functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL