validator

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2025 License: BSD-3-Clause Imports: 0 Imported by: 3

README

Validator

This package provides tools for validating various types of data in Go using predefined and user-defined validators.

Static Badge

GoDoc GitHub stars Go Report Card codecov

Versions

Stable Version GitHub Release GitHub Release

Installation

If you're using Go modules, add this package to your project with the following command:

go get -u github.com/gouef/validator

Usages

Basic Validation

This library allows easy validation of values using defined Constraint types.

package main

import (
	"fmt"
	"github.com/gouef/validator"
	"github.com/gouef/validator/constraints"
)

func main() {
	// Example usage for email validation
	emailValidator := constraints.Email{}
	errs := validator.Validate("example@example.com", emailValidator)

	if len(errs) > 0 {
		for _, err := range errs {
			fmt.Println("Error: ", err)
		}
	} else {
		fmt.Println("Email is valid.")
	}

	// Example validation for a value within a range
	rangeValidator := constraints.Range{Min: 10, Max: 100}
	errs = validator.Validate(50, rangeValidator)

	if len(errs) > 0 {
		for _, err := range errs {
			fmt.Println("Error: ", err)
		}
	} else {
		fmt.Println("Value is within the allowed range.")
	}
	
	// Example multiple constrains
	errs := validator.Validate("test@example.com", constraints.NotBlank{}, constraints.Email{})
	
	if len(errs) > 0 {
		for _, err := range errs {
			fmt.Println("Error: ", err)
		}
	} else {
		fmt.Println("Value is valid.")
	}
}

Custom Validator

If you want to add your own validator, simply implement the Constraint interface and write the Validate method to perform the validation.

package constraints

import "errors"

type GreaterThan100 struct{}

func (c GreaterThan100) Validate(value any) error {
	num, ok := value.(int)
	if !ok {
		return errors.New("this value must be an integer")
	}
	if num <= 100 {
		return errors.New("this value must be greater than 100")
	}
	return nil
}

You can use this custom validator just like the others:

gtValidator := constraints.GreaterThan100{}
errs := validator.Validate(150, gtValidator)

Or create Issue or PR.

Available Validators

This package includes several predefined validators:

  • Blank: Ensures the value is blank ("" or nil).
  • NotBlank: Ensures the value is not blank.
  • IsTrue: Ensures the value is true.
  • IsFalse: Ensures the value is false.
  • IsBool: Ensures the value is a boolean (true or false).
  • Currency: Ensures the value is a valid currency code.
  • Email: Ensures the value is a valid email address.
  • Language: Ensures the value is a valid language code without a region (e.g., en).
  • LanguageWithRegion: Ensures the value is a valid language code with a region (e.g., en-US).
  • Range: Ensures the value is within a defined range (e.g., a number between min and max).
  • Required: Ensures the value is not blank or nil.

Full list More at documentation

Configuration Options

Some validators allow configuration, for example:

  • The Email validator has an AllowNil() method to specify whether nil is allowed as a valid value.
emailValidator := constraints.Email{}
emailValidator.AllowNil() // Allows nil as a valid value
Testing

You can test validators using the testing package:

package validator_test

import (
	"testing"
	"github.com/gouef/validator"
	"github.com/gouef/validator/constraints"
	"github.com/stretchr/testify/assert"
)

func TestEmailValidator(t *testing.T) {
	emailValidator := constraints.Email{}
	errs := validator.Validate("test@example.com", emailValidator)
	assert.Empty(t, errs)

	errs = validator.Validate("invalid-email", emailValidator)
	assert.NotEmpty(t, errs)
}
Error Messages

When a validator returns an error, it is formatted as follows:

errors.New("this value is required")

If the validation is successful, an empty slice of errors is returned.

Contributing

Read Contributing

Contributors

JanGalek actions-user

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate(value any, constraints ...Constraint) []error

Validate function for validate list of Constraint

Example:

Types

type Constraint

type Constraint interface {
	Validate(value any) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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