validators

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2024 License: MIT Imports: 8 Imported by: 0

README

Validation Package

The package provides a set of validation utilities to check various conditions in data fields. These validators can be used to ensure data integrity and enforce specific requirements in your Go applications, making use only of native libraries to perform the validations.

Objective

The aim is to offer a simple and flexible way to perform data validation in Go applications in a customizable manner. By providing a set of validators, developers can easily incorporate data validation logic into their applications to ensure data consistency and meet specific validation requirements, without the need to write validation code from scratch, customizing validations according to the project's needs.

Installation

To use the package in your Go projects, type the following command in your terminal:

go get github.com/dariomatias-dev/go-validadores

Order of Validators

Validators should be organized following the following order: presence validator, type validator, and value validators. They should follow this order because otherwise, an error may occur if the sent value is not accepted by a validator that is placed later, even if it is a valid value.

This organization ensures that basic requirements, such as presence and type, are validated first before more specific validations about the value itself. By validating in this order, we can detect any potential errors early in the process, leading to a more robust and error-free validation system.

Just as there are no reasons to check if the value is of a specific type in value validators, which require the sent value to be of a certain type, as there are dedicated validators for this purpose, thus reducing the number of checks, making the validation process more efficient.

How to Use

To use the package, first import it into your project with the following import statement:

import "github.com/dariomatias-dev/go-validators"

I advise you to give it an alias to make package usage simpler and more efficient, like this:

import v "github.com/dariomatias-dev/go-validators"
Functionality of Validators

The validators have been created based on configurable functions, where the first set of parameters within the first pair of parentheses is used to configure the behavior of the validator, while the second set of parentheses receives the value to be validated. In the table of validators-available, it's referenced which validators require which value to be provided in order to perform validation.

Usage

To use the validations, use v. followed by the desired validation. In the first parenthesis, provide what is being requested, and if you don't want the default error message, insert the desired message afterwards. The validators will return two values: the first will be the error message if the provided value did not pass validation, and the second will be a boolean value indicating whether the validations should be halted or not. The second value is used in situations where, if the value did not pass the validator, subsequent validations cannot be executed because they will result in an error.

Validations can be performed in three distinct ways: individually, in combination, or within a map.


Validate Individual Value

A single validator is applied to a specific value.

Examples:

// Success
value := 4

err, _ := v.Min(3)(value) // nil, false
if err != nil {
    fmt.Println(err)
    return
}

// Error
value = 2

err, _ = v.Min(3)(value) // [error message], false
if err != nil {
    fmt.Println(err)
    return
}
Validate Value with Multiple Validators

Multiple validators are combined to validate a single value.

Examples:

validations := v.Validate(
    v.IsInt(),
    v.Min(3),
    v.Max(10),
)

// Success
value := 4
errors := validations(value) // Output: nil

if len(*errors) != 0 {
    fmt.Println(*errors)
    return
}

// Error
value = 2
errors = validations(value) // Output: [ error message(s) ]

if len(*errors) != 0 {
    fmt.Println(*errors)
    return
}
Validate Map

Each key of the map is validated separately with its own sets of validators.

Examples:

data := map[string]interface{}{
    "name":  "Name",
    "age":   18,
    "email": "[email protected]",
}

validations := v.Validators{
    "name": []v.Validator{
        v.IsString(),
        v.MinLength(3),
        v.MaxLength(20),
    },
    "age": []v.Validator{
        v.IsInt(),
        v.Min(18),
        v.Max(100),
    },
    "email": []v.Validator{
        v.Email(),
    },
}

validateMap := v.ValidateMap(validations)

// Success
errors := validateMap(data) // Output: nil
if errors != nil {
    fmt.Println(*errors)
    return
}

// Error
data["name"] = "Na"
errors = validateMap(data) // Output: {"name": [ error message ]}
if errors != nil {
    fmt.Println(*errors)
    return
}


/// Using struct

user := User{
    Name:  "Name",
    Age:   18,
    Email: "[email protected]",
}

// Success
errors := validateMap(data) // Output: nil
if errors != nil {
    fmt.Println(*errors)
    return
}

// Error
user.Email = "emailexample"
errors := validateMap(data) // {"email": [ "Invalid email" ]}
if errors != nil {
    fmt.Println(*errors)
    return
}
Validators Available
Validators Type Input
IsRequired Presence Error message
IsOptional Presence None
IsString Type Error message
IsNumber Type Error message
IsInt Type Error message
IsFloat Type Error message
IsBool Type Error message
IsArray Type Type of values*
Array settings*
Field validators*
Error message
IsNullString Type Error message
IsNullNumber Type Error message
IsNullInt Type Error message
IsNullFloat Type Error message
IsNullBool Type Error message
IsNullArray Type Type of values*
Array settings*
Field validators*
Error message
Email Value Minimum value*
Error messages
  • Invalid email
  • Value is not string
Min Value Minimum value*
Error message
Max Value Maximum value*
Error message
MinLength Value Minimum size*
Error message
MaxLength Value Maximum size*
Error message
IsAlpha Value Error message
IsAlphaSpace Value Error message
Regex Value Regex*
Error message*
Custom Value Custom validator*
Password Value Error message
URL Value Error message

All entries marked with (*) are mandatory.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate(
	validations ...Validator,
) func(value interface{}) *[]string

Applies all given validators to the passed value.

Configuration parameters:

  • value (any): value to be validated.
  • validations ([]Validator): validators.

Usage examples:

validations := v.Validate(
	v.IsInt(),
	v.Min(3),
	v.Max(10),
)

value := 4
validations(value) // Output: nil

value = 2
validations(value) // Output: [ error messages ]

func ValidateMap

func ValidateMap(
	fieldsValidations Validators,
) func(data any) *map[string][]string

Applies all validations to the respective fields.

Configuration parameters:

  • fieldsValidations (Validators): validators for each field.

Input value (map[string]any): Map to be validated.

Usage examples:

	data := map[string]interface{}{
		"name":  "Name",
		"age":   18,
		"email": "[email protected]",
	}

	validations := v.Validators{
		"name": []v.Validator{
			v.IsString(),
			v.MinLength(3),
			v.MaxLength(20),
		},
		"age": []v.Validator{
			v.IsInt(),
			v.Min(18),
			v.Max(100),
		},
		"email": []v.Validator{
			v.Email(),
		},
	}

 validateMap := v.ValidateMap(validations)

 validateMap(data) // Output: nil

 data["name"] = "Na"
 validateMap(data) // Output: { [error messages] }

Types

type Array

type Array struct {
	// AllowEmpty indicates whether the field can be empty or not.
	AllowEmpty bool
	// AllowEmptyErrorMessage is a custom error message to be displayed when the field is empty and not allowed.
	AllowEmptyErrorMessage string

	// MinLength specifies the minimum number of elements in the array.
	MinLength int
	// MinLengthErrorMessage is a custom error message to be displayed when the array has fewer elements than allowed.
	MinLengthErrorMessage string

	// MaxLength specifies the maximum number of elements in the array.
	MaxLength int
	// MaxLengthErrorMessage is a custom error message to be displayed when the array has more elements than allowed.
	MaxLengthErrorMessage string
}

Package validators provides configurations for the IsArray and IsNullArray validators.

type Validator

type Validator func(value interface{}) (
	errorMessage *string,
	stopLoop bool,
)

A function that takes a value to be validated and returns an error message along with a stop indicator for further validations. If the validation is successful, the error message should be nil and the stop indicator should be false. Otherwise, an error message is returned along with a boolean indicating whether to stop subsequent validations or not.

func Email

func Email(
	errorMessages ...string,
) Validator

Checks if the value is a validated email.

Configuration parameters:

- errorMessages (optional):

  • Invalid email.
  • value is not string.

Input value (string): value to be validated.

Usage examples:

value := "[email protected]"
v.Email()(value) // Output: nil, false

value = "emailexample"
v.Email()(value) // Output: [error message], false
v.Email("error")(value) // Output: "error", false
v.Email("", "error2")(nil) // Output: "error2", false

func EndsNotWith added in v0.1.1

func EndsNotWith(
	endsNotWith string,
	errorMessage ...string,
) Validator

Checks if the value does not end with a certain sequence.

Configuration parameters:

  • endsNotWith(string): character sequence that the value should not end with.
  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "message"
v.EndsNotWith("mes")(value) // Output: nil, false

v.EndsNotWith("age")(value) // Output: [error message], false
v.EndsNotWith("age", "error")(value) // Output: "error", false

func EndsWith added in v0.1.1

func EndsWith(
	endsWith string,
	errorMessage ...string,
) Validator

Checks whether the value ends with a given string.

Configuration parameters:

  • endsWith(string): character sequence that the value must start with.
  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "message"
v.EndsWith("age")(value) // Output: nil, false

value := "send message"
v.EndsWith("end")(value) // Output: [error message], false
v.EndsWith("end", "error")(value) // Output: "error", false

func IsAlpha

func IsAlpha(
	errorMessage ...string,
) Validator

Checks if the value contains only letters.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "abcABC"
v.IsAlpha()(value) // Output: nil, false

value = "abcABC "
v.IsAlpha()(value) // Output: [error message], false

value = "abcABC0123!@"
v.IsAlpha()(value) // Output: [error message], false

func IsAlphaSpace

func IsAlphaSpace(
	errorMessage ...string,
) Validator

Checks if the value contains only letters and spaces.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "abcABC"
v.IsAlphaSpace()(value) // Output: nil, false

value = "abcABC "
v.IsAlphaSpace()(value) // Output: nil, false

value = "abcABC0123!@"
v.IsAlphaSpace()(value) // Output: [error message], false

func IsArray

func IsArray(
	typeOfValues string,
	arraySettings Array,
	fieldValidators []Validator,
	errorMessage ...string,
) Validator

Checks if the value is a valid array.

Configuration parameters:

  • typeOfValues (string): type of array values.
  • arraySettings (Array): array settings.
  • fieldValidators ([]Validator): validators that must be applied to each value in the array.
  • errorMessage (string): custom error message (optional).

Input value ([]any): value to be validated.

Usage examples:

value1 := []string{}
IsArray(
	arraytype.String,
	Array{
		AllowEmpty: true,
	},
	[]Validator{},
)(value1) // Output: nil, false

value2 := nil
IsArray(
	arraytype.String,
	Array{},
	[]Validator{},
)(value2) // Output: [error message], true

value3 := []string{"a", "b"}
IsArray(
	arraytype.String,
	Array{
		MinLength: 3,
	},
	[]Validator{},
)(value3) // Output: [error message], true

func IsBool

func IsBool(
	errorMessage ...string,
) Validator

Checks if the value is a boolean.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): Value to be validated.

Usage examples:

value1 := true
v.IsBool()(value1) // Output: nil, false

value2 := nil
v.IsBool()(value2) // Output: [error message], true

value3 := 0
v.IsBool()(value3) // Output: [error message], true
v.IsBool("error")(value3) // Output: "error", true

func IsFloat

func IsFloat(
	errorMessage ...string,
) Validator

Checks if the value is a number or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value2 := 1.0
v.IsFloat()(value2) // Output: nil, false

value1 := 1
v.IsFloat()(value1) // Output: [error message], true

value3 := nil
v.IsFloat()(value3) // Output: [error message], true

value4 := ""
v.IsFloat()(value4) // Output: [error message], true
v.IsFloat("error")(value4) // Output: "error", true

func IsInt

func IsInt(
	errorMessage ...string,
) Validator

Checks if the value is a number or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := 1
v.IsInt()(value1) // Output: nil, false

value3 := nil
v.IsInt()(value3) // Output: [error message], true

value2 := 1.0
v.IsInt()(value2) // Output: [error message], true

value4 := ""
v.IsInt()(value4) // Output: [error message], true
v.IsInt("error")(value4) // Output: "error", true

func IsNullArray

func IsNullArray(
	typeOfValues string,
	arraySettings Array,
	fieldValidators []Validator,
	errorMessage ...string,
) Validator

Checks if the value is a valid array or nil.

Configuration parameters:

  • typeOfValues (string): type of array values.
  • arraySettings (Array): array settings.
  • fieldValidators ([]Validator): validators that must be applied to each value in the array.
  • errorMessage (string): custom error message (optional).

Input value ([]any): value to be validated

Usage examples:

value1 := []string{}
IsNullArray(
	arraytype.String,
	Array{
		AllowEmpty: true,
	},
	[]Validator{},
)(value1) // Output: nil, false

value2 := nil
IsNullArray(
	arraytype.String,
	Array{
		MinLength: 3,
	},
	[]Validator{},
)(value2) // Output: nil, false

value3 := []string{"a", "b"}
IsNullArray(
	arraytype.String,
	Array{
		MinLength: 3,
	},
	[]Validator{},
)(value3) // Output: [error message], true

func IsNullBool

func IsNullBool(
	errorMessage ...string,
) Validator

Checks if the value is a boolean or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): Value to be validated.

Usage examples:

value1 := true
v.IsNullBool()(value1) // Output: nil, false

value2 := nil
v.IsNullBool()(value2) // Output: nil, true

value3 := 0
v.IsNullBool()(value3) // Output: [error message], true
v.IsNullBool("error")(value3) // Output: "error", true

func IsNullFloat

func IsNullFloat(
	errorMessage ...string,
) Validator

Checks if the value is a number or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := nil
v.IsNullFloat()(value1) // Output: nil, true

value2 := 1.0
v.IsNullFloat()(value2) // Output: nil, false

value3 := 1
v.IsNullFloat()(value3) // Output: [error message], true

value4 := ""
v.IsNullFloat()(value4) // Output: [error message], true
v.IsNullFloat("error")(value4) // Output: "error", true

func IsNullInt

func IsNullInt(
	errorMessage ...string,
) Validator

Checks if the value is a number or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := nil
v.IsNullInt()(value1) // Output: nil, true

value2 := 1
v.IsNullInt()(value2) // Output: nil, false

value3 := 1.0
v.IsNullInt()(value3) // Output: [error message], true

value4 := ""
v.IsNullInt()(value4) // Output: [error message], true
v.IsNullInt("error")(value4) // Output: "error", true

func IsNullNumber

func IsNullNumber(
	errorMessage ...string,
) Validator

Checks if the value is a number or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := nil
v.IsNullNumber()(value1) // Output: nil, true

value2 := 1
v.IsNullNumber()(value2) // Output: nil, false

value3 := 1.0
v.IsNullNumber()(value3) // Output: nil, false

value4 := ""
v.IsNullNumber()(value4) // Output: [error message], true
v.IsNullNumber("error")(value4) // Output: "error", true

func IsNullString

func IsNullString(
	errorMessage ...string,
) Validator

Checks if the value is a string or null.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := nil
v.IsNullString()(value1) // Output: nil, true

value2 := "Name"
v.IsNullString()(value2) // Output: nil, false

value3 := 0
v.IsNullString()(value3) // Output: [error message], true
v.IsNullString("error")(value3) // Output: "error", true

func IsNumber

func IsNumber(
	errorMessage ...string,
) Validator

Checks if the value is a number.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := 1
v.IsNumber()(value1) // Output: nil, false

value2 := 1.0
v.IsNumber()(value2) // Output: nil, false

value3 := nil
v.IsNumber()(value3) // Output: [error message], true

value4 := ""
v.IsNumber()(value4) // Output: [error message], true
v.IsNumber("error")(value4) // Output: "error", true

func IsOptional

func IsOptional() Validator

Allows the field value to be optional.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value2 := nil
v.IsOptional()(value2) // Output: nil, true

value1 := "Name"
v.IsOptional()(value1) // Output: nil, false

func IsRequired

func IsRequired(
	errorMessage ...string,
) Validator

Checks if the value was provided.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := "Name"
v.IsRequired()(value1) // Output: nil, false

value2 := nil
v.IsRequired()(value2) // Output: [error message], true

func IsString

func IsString(
	errorMessage ...string,
) Validator

Checks if the value is a string.

Configuration parameters:

  • errorMessage (string): custom error message (optional).

Input value (any): value to be validated.

Usage examples:

value1 := "Name"
v.IsString()(value1) // Output: nil, false

value2 := nil
v.IsString()(value2) // Output: [error message], true

value3 := 0
v.IsString()(value3) // Output: [error message], true
v.IsString("error")(value3) // Output: "error", true

func Max

func Max(
	max interface{},
	errorMessage ...string,
) Validator

Checks if the value is greater than the specified maximum value.

Configuration parameters:

  • max(int | int32| int64 | float32 | float64): maximum value that the value must have.
  • errorMessage (string): custom error message (optional).

Input value (int | int32| int64 | float32 | float64): value to be validated.

Usage examples:

value := 3
v.Max(5)(value) // Output: nil, false

value := 6
v.Max(5)(value) // Output: [error message], false
v.Max(5, "error")(value) // Output: "error", false

func MaxLength

func MaxLength(
	maxLength interface{},
	errorMessage ...string,
) Validator

Checks if a string has the specified maximum length.

Configuration parameters:

  • maxLength (int): maximum length that the string must have.
  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "Name"
v.MaxLength(5)(value) // Output: nil, false

value = "Name is..."
v.MaxLength(5)(value) // Output: [error message], false
v.MaxLength(5, "error")(value) // Output: "error", false

func Min

func Min(
	min interface{},
	errorMessage ...string,
) Validator

Checks if the value is less than the specified minimum value.

Configuration parameters:

  • min(int | int32| int64 | float32 | float64): minimum value that the value must have.
  • errorMessage (string): custom error message (optional).

Input value (int | int32| int64 | float32 | float64): value to be validated.

Usage examples:

value := 6
v.Min(5)(value) // Output: nil, false

value := 3
v.Min(5)(value) // Output: [error message], false
v.Min(5, "error")(value) // Output: "error", false

func MinLength

func MinLength(
	minLength interface{},
	errorMessage ...string,
) Validator

Checks if a string has the specified minimum length.

Configuration parameters:

  • minLength (int): minimum length that the string must have.
  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "Name"
v.MinLength(3)(value) // Output: nil, false

value = "Na"
v.MinLength(3)(value) // Output: [error message], false
v.MinLength(3, "error")(value) // Output: "error", false

func OneOf added in v0.1.1

func OneOf(
	arrayType string,
	options any,
	errorMessage ...string,
) Validator

Checks if the value is within certain options.

Configuration parameters:

  • arrayType (string): type of option array values.
  • options ([]string | []int | []float64): value options.
  • errorMessage (string): custom error message (optional).

Input value (string | int | float64): value to be validated.

Usage examples:

options := []string{"one", "two", "three"}
value := "three"
v.OneOf(options)(value) // Output: nil, false

value = "four"
v.OneOf(options)(value) // Output: [error message], false
v.OneOf(options, "error")(value) // Output: "error", false

func Password

func Password(
	errorMessage ...string,
) Validator

Checks whether the value contains lowercase and uppercase letters, numbers and special characters.

Configuration parameters:

  • errorMessage (string): custom error message.

Input value (string): value to be validated.

Usage examples:

value := "abcABC0123!@"
v.Password()(value) // Output: nil, false

value = "abc"
v.Password()(value) // Output: [error message], false
v.Password("error")(value) // Output: "error", false

func Regex

func Regex(
	regex string,
	errorMessage string,
) Validator

Checks if the value meets the given regex.

Configuration parameters:

  • regex (string): regex that will be used to validate value.
  • errorMessage (string): custom error message.

Input value (string): value to be validated.

Usage examples:

regex := "[A-Z]"
errorMessage := "The value must be in capital letters"

value := "ABC"
v.Regex(regex, errorMessage)(value) // Output: nil, false

value = "abc"
v.Regex(regex, errorMessage)(value) // Output: [error message], false

func StartsNotWith added in v0.1.1

func StartsNotWith(
	startsNotWith string,
	errorMessage ...string,
) Validator

Checks if the value does not start with a certain sequence.

Configuration parameters:

  • startWith(string): character sequence that the value should not start with.
  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "message"
v.StartsNotWith("es")(value) // Output: nil, false

value := "send message"
v.StartsNotWith("send")(value) // Output: [error message], false
v.StartsNotWith("send", "error")(value) // Output: "error", false

func StartsWith added in v0.1.1

func StartsWith(
	startWith string,
	errorMessage ...string,
) Validator

Checks if the value starts with a given sequence.

Configuration parameters:

  • startWith(string): character sequence that the value must start with.
  • errorMessage (string): custom error message (optional).

Input value (string): value to be validated.

Usage examples:

value := "message"
v.StartsWith("mes")(value) // Output: nil, false

value := "send message"
v.StartsWith("end")(value) // Output: [error message], false
v.StartsWith("end", "error")(value) // Output: "error", false

func URL

func URL(
	errorMessage ...string,
) Validator

Checks if the value is a valid URL.

Configuration parameters:

  • errorMessage (string): custom error message.

Input value (string): value to be validated.

Usage examples:

value := "golang.org"
v.URL()(value) // Output: nil, false

value = "golang"
v.URL()(value) // Output: [error message], false
v.URL("error")(value) // Output: "error", false

type Validators

type Validators map[string][]Validator

Represents a validation map where the keys are the names of the fields to be validated, with each field having slices of associated validators.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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