validator

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2025 License: ISC Imports: 9 Imported by: 0

README

Validator

GitHub Tag Go Reference License Go Report Card Contributors Issues

validator is a Go package that provides a flexible and extensible validation framework with support for localization. It leverages the go-playground/validator package for validation and go-universal/i18n for localization.

Features

  • Custom validation rules
  • Localized error messages
  • Struct and variable validation
  • Support for various data types and formats

Installation

To install validator, use the following command:

go get github.com/go-universal/validator

Usage

Basic Usage

Here's a basic example of how to use validator:

package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
    "github.com/go-universal/i18n"
    "github.com/go-universal/validator"
    "golang.org/x/text/language"
)

func main() {
    // Initialize the validator
    v := validator.NewValidator(
        validator.New(),
        validator.WithTranslator(
            i18n.NewTranslator("en", language.English),
            "",
        ),
    )

    // Add custom validation rule
    v.AddValidation("is_valid", func(fl validator.FieldLevel) bool {
        return fl.Field().String() == "valid"
    })
    v.AddTranslation("en", "is_valid", "{field} must be valid")

    // Validate a variable
    err := v.Var("en", "my_field", "valid", "required,is_valid")
    if err.HasInternalError() {
        fmt.Println("Internal error:", err.InternalError())
    } else if err.HasValidationErrors() {
        fmt.Println("Validation errors:", err)
    } else {
        fmt.Println("Validation passed")
    }
}
Struct Validation

You can also validate structs with validator:

package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
    "github.com/go-universal/i18n"
    "github.com/go-universal/validator"
    "golang.org/x/text/language"
)

type TestStruct struct {
    Field string `validate:"required,is_valid"`
}

func main() {
    // Initialize the validator
    v := validator.NewValidator(
        validator.New(),
        validator.WithTranslator(
            i18n.NewTranslator("en", language.English),
            "",
        ),
    )

    // Add custom validation rule
    v.AddValidation("is_valid", func(fl validator.FieldLevel) bool {
        return fl.Field().String() == "valid"
    })
    v.AddTranslation("en", "is_valid", "{field} must be valid")

    // Validate a struct
    ts := TestStruct{Field: "valid"}
    err := v.Struct("en", ts)
    if err.HasInternalError() {
        fmt.Println("Internal error:", err.InternalError())
    } else if err.HasValidationErrors() {
        fmt.Println("Validation errors:", err)
    } else {
        fmt.Println("Validation passed")
    }
}
Custom Validators

You can add custom validators to validator:

package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
    "github.com/go-universal/i18n"
    "github.com/go-universal/validator"
    "golang.org/x/text/language"
)

func main() {
    // Initialize the validator
    v := validator.NewValidator(
        validator.New(),
        validator.WithTranslator(
            i18n.NewTranslator("en", language.English),
            "",
        ),
    )

    // Add custom validation rule
    v.AddValidation("is_valid", func(fl validator.FieldLevel) bool {
        return fl.Field().String() == "valid"
    })
    v.AddTranslation("en", "is_valid", "{field} must be valid")

    // Validate a variable
    err := v.Var("en", "my_field", "invalid", "required,is_valid")
    if err.HasInternalError() {
        fmt.Println("Internal error:", err.InternalError())
    } else if err.HasValidationErrors() {
        fmt.Println("Validation errors:", err)
    } else {
        fmt.Println("Validation passed")
    }
}

License

This project is licensed under the ISC License. See the LICENSE file for details.

Acknowledgements

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Options

type Options func(*i18nValidator)

Options defines a function type that modifies I18nValidator.

func WithAlphaNumericPersianValidator

func WithAlphaNumericPersianValidator(messages map[string]string, rule ...string) Options

WithAlphaNumericPersianValidator adds validation for English, Persian letters, and numbers.

func WithAlphaNumericValidator

func WithAlphaNumericValidator(messages map[string]string, rule ...string) Options

WithAlphaNumericValidator adds validation for English letters and numbers.

func WithFiberTagResolver

func WithFiberTagResolver() Options

WithFiberTagResolver returns an option for configuring the I18nValidator to resolve field names from various tags. It checks the "field", "json", "form", and "xml" tags in priority order. If no valid tag is found, it defaults to the field name. Fields with the "-" tag are ignored.

func WithIranianCreditNumberValidator

func WithIranianCreditNumberValidator(messages map[string]string, rule ...string) Options

WithIranianCreditNumberValidator adds validation for 16-digit Iranian credit card numbers.

func WithIranianIBANValidator

func WithIranianIBANValidator(messages map[string]string, rule ...string) Options

WithIranianIBANValidator adds validation for 24-digit Iranian IBAN numbers.

func WithIranianIdNumberValidator

func WithIranianIdNumberValidator(messages map[string]string, rule ...string) Options

WithIranianIdNumberValidator adds validation for Iranian birth certificate numbers.

func WithIranianMobileValidator

func WithIranianMobileValidator(messages map[string]string, rule ...string) Options

WithIranianMobileValidator adds validation for 11-digit Iranian mobile numbers.

func WithIranianNationalCodeValidator

func WithIranianNationalCodeValidator(messages map[string]string, rule ...string) Options

WithIranianNationalCodeValidator adds validation for 10-digit Iranian national ID numbers.

func WithIranianPhoneValidator

func WithIranianPhoneValidator(messages map[string]string, rule ...string) Options

WithIranianPhoneValidator adds validation for 11-digit Iranian phone numbers.

func WithIranianPostalCodeValidator

func WithIranianPostalCodeValidator(messages map[string]string, rule ...string) Options

WithIranianPostalCodeValidator adds validation for 10-digit Iranian postal codes.

func WithJalaaliValidator

func WithJalaaliValidator(messages map[string]string, rule ...string) Options

WithJalaaliValidator adds validation for Jalaali datetime strings.

func WithTranslator

func WithTranslator(translator i18n.Translator, prefix string) Options

WithTranslator configures the I18nValidator with a translator and a translation key prefix.

func WithUsernameValidator

func WithUsernameValidator(messages map[string]string, rule ...string) Options

WithUsernameValidator adds a validation rule for usernames (letters, numbers, underscores).

type Translatable

type Translatable interface {
	// TranslateError returns a localized error message for a given rule and field.
	TranslateError(locale, rule, field string) string
}

Translatable defines an interface for translating validation error messages.

type TranslatableField

type TranslatableField interface {
	// TranslateTitle returns a localized display name for a given field.
	TranslateTitle(locale, field string) string
}

TranslatableField defines an interface for translating field names.

type ValidationError

type ValidationError interface {
	// HasError checks if there is any validation or internal error.
	HasError() bool

	// HasInternalError checks if there is a internal system error.
	HasInternalError() bool

	// HasValidationErrors returns true if there are validation errors.
	HasValidationErrors() bool

	// IsFailed checks if a specific field has validation errors.
	IsFailed(field string) bool

	// IsFailedOn checks if a specific field failed on a given validation rule.
	IsFailedOn(field, rule string) bool

	// InternalError returns the internal system error related to the validation process, if any.
	InternalError() error

	// Errors returns a nested map of validation errors for each field and rule.
	Errors() map[string]map[string]string

	// Messages returns a map of validation error messages for each field.
	Messages() map[string][]string

	// Rules returns a map of validation error rules for each field.
	Rules() map[string][]string

	// MarshalJSON serializes the validation errors into JSON format.
	MarshalJSON() ([]byte, error)

	// String returns a string representation of all validation errors.
	String() string

	// AddError records a validation error for a specific field and validation rule.
	AddError(field, rule string, message ...string)
}

ValidationError defines an interface for managing validation errors.

func NewEmptyError

func NewEmptyError() ValidationError

NewEmptyError creates a new empty ValidationError without any internal error.

func NewError

func NewError(err error) ValidationError

NewError creates a new ValidationError with an internal error.

type Validator

type Validator interface {
	// AddValidation registers a custom validation rule with a custom validation function.
	AddValidation(rule string, f validator.Func)

	// AddTranslation adds a translation message for a validation rule in a specified locale.
	AddTranslation(locale, rule, message string, options ...i18n.PluralOption)

	// Struct validates an entire struct based on its defined validation rules.
	// Returns validation errors in the provided locale, defaulting to the translator locale if empty.
	Struct(locale string, value any) ValidationError

	// StructExpect validates a struct while ignoring specified fields.
	// Returns validation errors in the provided locale, defaulting to the translator locale if empty.
	StructExpect(locale string, value any, fields ...string) ValidationError

	// StructPartial validates only specified fields of a struct.
	// Returns validation errors in the provided locale, defaulting to the translator locale if empty.
	StructPartial(locale string, value any, fields ...string) ValidationError

	// Var validates a single variable against a rule with optional custom messages.
	Var(locale, name string, value any, rules string) ValidationError

	// VarWithValue validates a variable against another using a rule with custom error messages.
	VarWithValue(locale, name string, value any, other any, rules string) ValidationError
}

Validator defines an interface for localized validation functionality.

func NewValidator

func NewValidator(validator *validator.Validate, options ...Options) Validator

NewValidator creates a new Validator instance with optional configurations. Initializes the I18nValidator with the provided translator and base validator, and applies any options.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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