Categorygithub.com/dariomatias-dev/go-validators
modulepackage
0.2.0
Repository: https://github.com/dariomatias-dev/go-validators.git
Documentation: pkg.go.dev

# 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-validators

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, or within a json.

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)  // The minimum value is 3, but it received 2, false
if err != nil {
    fmt.Println(err)
    return
}

Validate JSON

Validates the provided JSON based on the validators defined for each field, returning an error if there is an inconsistency, or assigning the values from the JSON to the provided struct if there are no errors.

Examples:

type UserModel struct {
    Name  string `json:"name"  validates:"required;isString;minLength=3;maxLength=20"`
    Age   int    `json:"age"   validates:"required;isInt;min=18;max=100"`
    Email string `json:"email" validates:"required;email"`
}
user := UserModel{}

json := `{
    "name":  "Name",
    "age":   18,
    "email": "[email protected]"
}`

// Success
err := Validate(&user, json)           // Output: nil
if err != nil {
    fmt.Println(err)
    return
}

// Error
json := `{
    "name":  "Name",
    "age":   16,
    "email": "[email protected]"
}`
err := Validate(&user, json)           // Output: {"age":["The minimum value is 18, but it received 16."]}
if err != nil {
    fmt.Println(err)
    return
}

Validators Available

ValidatorTypeInputValue Type
RequiredPresence
  • Error message
any
IsStringType
  • Error message
string
IsNumberType
  • Error message
int | float
IsIntType
  • Error message
int
IsFloatType
  • Error message
float
IsBoolType
  • Error message
bool
IsArrayType
  • Field validators*
  • Error message
slice | array
IsNullStringType
  • Error message
nil | string
IsNullNumberType
  • Error message
nil | int | float
IsNullIntType
  • Error message
nil | int
IsNullFloatType
  • Error message
nil | float
IsNullBoolType
  • Error message
nil | bool
IsNullArrayType
  • Field validators*
  • Error message
nil | slice | array
EmailValue
  • Minimum value*
  • Error messages
    • Invalid email
    • Value is not string
string
PasswordValue
  • Error message
string
MinValue
  • Minimum value*
  • Error message
int | int32 | int64 | float32 | float64
MaxValue
  • Maximum value*
  • Error message
int | int32 | int64 | float32 | float64
LengthValue
  • Size*
  • Error message
string | slice | array
MinLengthValue
  • Minimum size*
  • Error message
string | slice | array
MaxLengthValue
  • Maximum size*
  • Error message
string | slice | array
IsAlphaValue
  • Error message
string
IsAlphaNumValue
  • Error message
string
IsAlphaSpaceValue
  • Error message
string
IsAlphaNumSpaceValue
  • Error message
string
StartsWithValue
  • Starts with*
  • Error message
string
StartsNotWithValue
  • Starts not with*
  • Error message
string
EndsWithValue
  • Ends with*
  • Error message
string
EndsNotWithValue
  • Ends not with*
  • Error message
string
RegexValue
  • Regex*
  • Error message
string
UrlValue
  • Error message
string
UuidValue
  • Version (Default Version 5)
  • Error message
string
OneOfValue
  • Options*
  • Error message
string
CustomValue
  • Custom validator*
any

All entries marked with (*) are mandatory.


Donations

Help maintain the project with donations.

"Buy Me A Coffee"

# Functions

Checks if the value is a validated email.
Checks if the value does not end with a certain sequence.
Checks whether the value ends with a given string.
Checks if the value contains only letters.
Checks if the value contains only letters and numbers.
Checks if the value contains only letters, numbers and spaces.
Checks if the value contains only letters and spaces.
Checks if the value is a valid array.
Checks if the value is a boolean.
Checks if the value is a number or null.
Checks if the value is a number or null.
Checks if the value is a valid array or null.
Checks if the value is a boolean or null.
Checks if the value is a number or null.
Checks if the value is a number or null.
Checks if the value is a number or null.
Checks if the value is a string or null.
Checks if the value is a number.
Checks if the value is a string.
Checks if a string/slice/array has the specified length.
Checks if the value is greater than the specified maximum value.
Checks if a string/slice/array has the specified maximum length.
Checks if the value is less than the specified minimum value.
Checks if a string/slice/array has the specified minimum length.
Checks if the value is within certain options.
Checks whether the value contains lowercase and uppercase letters, numbers and special characters.
Checks if the value meets the given regex.
Checks if the value was provided.
Checks if the value does not start with a certain sequence.
Checks if the value starts with a given sequence.
Checks if the value is a valid Url.
Checks if the value is a valid UUID.
Validates the provided JSON based on the validators defined for each field.

# Type aliases

A function that takes a value to be validated and returns an error message along with a stop indicator for further validations.