valgo

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2025 License: MIT Imports: 12 Imported by: 22

README

Valgo

Valgo is a type-safe, expressive, and extensible validator library for Golang. Valgo is built with generics, so Go 1.18 or higher is required.

Valgo differs from other Golang validation libraries in that the rules are written in functions and not in struct tags. This allows greater flexibility and freedom when it comes to where and how data is validated.

Additionally, Valgo supports customizing and localizing validation messages.

Quick example

Here is a quick example:

package main

import v "github.com/cohesivestack/valgo"

func main() {
  val := v.Is(
    v.String("Bob", "full_name").Not().Blank().OfLengthBetween(4, 20),
    v.Number(17, "age").GreaterThan(18),
  )

  if !val.Valid() {
    out, _ := json.MarshalIndent(val.ToError(), "", "  ")
    fmt.Println(string(out))
  }
}

output:

{
  "age": [
    "Age must be greater than \"18\""
  ],
  "full_name": [
    "Full name must have a length between \"4\" and \"20\""
  ]
}

v0.x.x and backward compatibility

Valgo is in its early stages, so backward compatibility won't be guaranteed until v1.

Valgo is used in production by Statsignal, but we want community feedback before releasing version 1.

🚨 Breaking Changes

v0.6.0 — String Length Validation

Starting from v0.6.0, all string length validators now measure length in characters (runes) instead of bytes. This means that multi-byte UTF-8 characters (such as Japanese/Chinese/Korean characters, accented letters, and other international characters) are now counted as one character each, making the validators more intuitive for international (i18n) applications.

What Changed
  • MaxLength, MinLength, OfLength, and OfLengthBetween now use utf8.RuneCountInString.
v0.7.0 — Numeric Validators: Codegen removed → one generic per family

We removed code generation for numeric validators and replaced it with type-safe generics. Each numeric family now has one generic validator type that replaces all the previous width-specific types.

Replacements (numeric families)

Signed integers

  • New: ValidatorInt[T ~int | ~int8 | ~int16 | ~int32 | ~int64] Replaces: ValidatorInt, ValidatorInt8, ValidatorInt16, ValidatorInt32, ValidatorInt64

Unsigned integers

  • New: ValidatorUint[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64] Replaces: ValidatorUint, ValidatorUint8, ValidatorUint16, ValidatorUint32, ValidatorUint64

Floats

  • New: ValidatorFloat[T ~float32 | ~float64] Replaces: ValidatorFloat32, ValidatorFloat64
Impact (when you declare variables/params)

Most call sites don’t change—constructors like v.Int16(...), v.Uint64(...), v.Float32(...) still exist and now return the generic validators. You only need to update declared types of variables/parameters.

Before (pre-v0.7.0)

age := int16(10)
var validatorAge ValidatorInt16
validatorAge = v.Int16(age).EqualTo(18)

After (v0.7.0+)

age := int16(10)
var validatorAge *ValidatorInt[int16]
validatorAge = v.Int16(age).EqualTo(18)
Not affected
  • Non-numeric validators (e.g., string/time/etc.) are unchanged.
Migration

If your code relied on byte length (using len semantics), use the new explicit byte-based validators:

  • MaxBytes
  • MinBytes
  • OfByteLength
  • OfByteLengthBetween
Example
s := "你好" // 2 characters (runes), 6 bytes
japanese := "こんにちは" // 5 characters (runes), 15 bytes

// New default: counts characters (runes)
v.String(s, "field").MaxLength(2)        // ✅ passes
v.String(japanese, "field").MaxLength(5) // ✅ passes

// Byte-based: counts bytes
v.String(s, "field").MaxBytes(6)         // ✅ passes
v.String(japanese, "field").MaxBytes(15) // ✅ passes

Table of content

Getting started

Install in your project:

go get github.com/cohesivestack/valgo

Import in your code:

import v github.com/cohesivestack/valgo

Note: You can use any other aliases instead of v or just reference the package valgo directly.

Using Valgo

Validation session

The Validation session in Valgo is the main structure for validating one or more values. It is called 'Validation' in code.

A validation session will contain one or more Validators, where each Validator will have the responsibility to validate a value with one or more rules.

There are multiple functions to create a Validation session, depending on the requirements:

  • New(),
  • Is(...),
  • In(...),
  • InRow(...),
  • InCell(...),
  • Check(...),
  • AddErrorMessage(...)

Is(...) is likely to be the most frequently used function in your validations. When Is(...) is called, the function creates a validation and receives a validator at the same time. In the next section, you will learn more about the Is(...) function.

Is(...) function

The Is(...) function allows you to pass one or multiple Validators, each with their respective values and rules for validation. This creates a Validation session, which can be used to validate multiple values.

In the following example, we pass multiple Validators for the full_name, age, and status values to the Is(...) function:

val := v.Is(
  v.String("Bob", "full_name").Not().Blank().OfLengthBetween(4, 20),
  v.Number(17, "age").GreaterThan(18),
  v.String("singl", "status").InSlice([]string{"married", "single"})
)

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "age": [
    "Age must be greater than \"18\""
  ],
  "full_name": [
    "Full name must have a length between \"4\" and \"20\""
  ],
  "status": [
    "Status is not valid"
  ]
}

Validation.Valid() function

A Validation session provides this function, which returns either true if all their validators are valid or false if any one of them is invalid.

In the following example, even though the Validator for age is valid, the Validator for status is invalid, making the entire Validator session invalid.

val := v.Is(
  v.Number(21, "age").GreaterThan(18),
  v.String("singl", "status").InSlice([]string{"married", "single"}),
)

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "status": [
    "Status is not valid"
  ]
}

Validation.IsValid(...) function

This function allows checking if a specific value in a Validation session is valid or not. This is very useful for conditional logic.

The following example prints an error message if the age value is invalid.

val := v.Is(v.Number(16, "age").GreaterThan(18)).
  Is(v.String("single", "status").InSlice([]string{"married", "single"}))

if !val.IsValid("age") {
  fmt.Println("Warning: someone underage is trying to sign up")
}

output:

Warning: someone underage is trying to sign up

When you work with nested or indexed namespaces (for example using In(...) or InRow(...)), IsValid(...) also understands parent paths: if a deeply nested field is invalid, all of its parent namespaces are considered invalid as well.

val := v.In("person",
  v.InRow("addresses", 0,
    v.Is(
      v.String("", "line1").Not().Blank(), // invalid
      v.String("Main St", "line2").Not().Blank(),
    ),
  ),
)

// Leaf field is invalid
_ = val.IsValid("person.addresses[0].line1") // false

// Parent namespaces of that field are also invalid
_ = val.IsValid("person.addresses[0]") // false
_ = val.IsValid("person.addresses")    // false
_ = val.IsValid("person")              // false

// Unrelated namespaces remain valid
_ = val.IsValid("person.addresses[1]") // true

This lets you write concise checks like if !val.IsValid("person.addresses") { ... } without needing to know exactly which nested field failed.

In(...) function

The In(...) function executes one or more validators in a namespace, so the value names in the error result are prefixed with this namespace. This is useful for validating nested structures.

In the following example we are validating the Person and the nested Address structure. We can distinguish the errors of the nested Address structure in the error results.

type Address struct {
  Name string
  Street string
}

type Person struct {
  Name string
  Address Address
}

p := Person{"Bob", Address{"", "1600 Amphitheatre Pkwy"}}

val := v.
  Is(v.String(p.Name, "name").OfLengthBetween(4, 20)).
  In("address", v.Is(
    String(p.Address.Name, "name").Not().Blank(),
    String(p.Address.Street, "street").Not().Blank(),
  ))

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "address.name": [
    "Name can't be blank"
  ],
  "name": [
    "Name must have a length between \"4\" and \"20\""
  ]
}

InRow(...) function

The InRow(...) function executes one or more validators in a namespace similar to the In(...) function, but with indexed namespace. So, the value names in the error result are prefixed with this indexed namespace. It is useful for validating nested lists in structures.

In the following example we validate the Person and the nested list Addresses. The error results can distinguish the errors of the nested list Addresses.

type Address struct {
  Name   string
  Street string
}

type Person struct {
  Name      string
  Addresses []Address
}

p := Person{
  "Bob",
  []Address{
    {"", "1600 Amphitheatre Pkwy"},
    {"Home", ""},
  },
}

val := v.Is(String(p.Name, "name").OfLengthBetween(4, 20))

for i, a := range p.Addresses {
  val.InRow("addresses", i, v.Is(
    v.String(a.Name, "name").Not().Blank(),
    v.String(a.Street, "street").Not().Blank(),
  ))
}

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "addresses[0].name": [
    "Name can't be blank"
  ],
  "addresses[1].street": [
    "Street can't be blank"
  ],
  "name": [
    "Name must have a length between \"4\" and \"20\""
  ]
}

InCell(...) function

The InCell(...) function executes one or more validators in an indexed namespace where the target is a scalar value (e.g., entries of a primitive slice). The value names in the error result are prefixed with this indexed namespace. It is useful for validating lists of primitive values.

In the following example, we validate a list of tag names. The error results can distinguish the errors for each list entry.

tags := []string{"", ""}

val := v.New()
for i, tag := range tags {
  val.InCell("tags", i, v.Is(
    v.String(tag, "name").Not().Blank(),
  ))
}

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "tags[0]": [
    "Name can't be blank"
  ],
  "tags[1]": [
    "Name can't be blank"
  ]
}

Check(...) function

The Check(...) function, similar to the Is(...) function, however with Check(...) the Rules of the Validator parameter are not short-circuited, which means that regardless of whether a previous rule was valid, all rules are checked.

This example shows two rules that fail due to the empty value in the full_name Validator, and since the Validator is not short-circuited, both error messages are added to the error result.

val := v.Check(v.String("", "full_name").Not().Blank().OfLengthBetween(4, 20))

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "full_name": [
    "Full name can't be blank",
	  "Full name must have a length between \"4\" and \"20\""
  ]
}

If(...) function

The If(...) function is similar to Merge(...), but merges the Validation session only when the condition is true, and returns the same Validation instance. When the condition is false, no operation is performed and the original instance is returned unchanged.

This function allows you to write validation code in a more fluent and compact way, especially useful for conditional merging of validation sessions without the need for separate if statements or complex branching logic.


// Only merge admin validation if user is admin
val := v.
  Is(v.String(username, "username").Not().Blank()).
  If(isAdmin, v.Is(v.String(role, "role").EqualTo("admin")))

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

Do(...) function

The Do(...) function executes the given function with the current Validation instance and returns the same instance. This allows you to extend a validation chain with additional or conditional rules in a concise way.

val := v.
  Is(v.String(username, "username").Not().Blank()).
  Do(func(val *v.Validation) {
    if isAdmin {
      val.Is(v.String(role, "role").EqualTo("admin"))
    }
  })

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

When(...) function

The When(...) function is similar to Do(...), but executes the given function only when the condition is true, and returns the same Validation instance. When the condition is false, no operation is performed and the original instance is returned unchanged.

This function provides a more concise way to add conditional validation logic compared to using Do(...) with an internal if statement.

val := v.
  Is(v.String(username, "username").Not().Blank()).
  When(isAdmin, func(val *v.Validation) {
    val.Is(v.String(role, "role").EqualTo("admin"))
  })

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

AddErrorMessage(...) function

The AddErrorMessage function allows to add an error message to a Validation session without executing a field validator. This function takes in two arguments: name, which is the name of the field for which the error message is being added, and message, which is the error message being added to the session.

When an error message is added using this function, the Validation session is marked as invalid, indicating that at least one validation error has occurred.

One use case for the AddErrorMessage function is to add a general error message for the validation of an entity structure. As shown in the example below, if you have an entity structure for an address and need to validate multiple fields within it, such as the city and street, you can use AddErrorMessage to include a general error message for the entire address in case any of the fields fail validation.

type Address struct {
  City string
  Street string
}

a := Address{"", "1600 Amphitheatre Pkwy"}

val := v.Is(
  v.String(a.city, "city").Not().Blank(),
  v.String(a.Street, "street").Not().Blank(),
)

if !val.Valid() {
  v.AddErrorMessage("address", "The address is wrong!")

  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "address": [
    "The address is wrong!"
  ],
  "city": [
    "City can't be blank"
  ]
}

It's worth noting that there may be other use cases for this function as well.

Merging two Validation sessions with Validation.Merge( ... )

Using Merge(...) you can merge two Validation sessions. When two validations are merged, errors with the same value name will be merged. It is useful for reusing validation logic.

The following example merges the Validation session returned by the validatePreStatus function. Since both Validation sessions validate a value with the name status, the error returned will return two error messages, and without duplicate the Not().Blank() error message rule.


type Record struct {
  Name   string
  Status string
}

validatePreStatus := func(status string) *Validation {
  regex, _ := regexp.Compile("pre-.+")

  return v.
    Is(v.String(status, "status").Not().Blank().MatchingTo(regex))
}

r := Record{"Classified", ""}

val := v.Is(
  v.String(r.Name, "name").Not().Blank(),
  v.String(r.Status, "status").Not().Blank(),
)

val.Merge(validatePreStatus(r.Status))

if !val.Valid() {
  out, _ := json.MarshalIndent(val.ToError(), "", "  ")
  fmt.Println(string(out))
}

output:

{
  "status": [
	  "Status can't be blank",
	  "Status must match to \"pre-.+\""
  ]
}

New() function

This function allows you to create a new Validation session without a Validator. This is useful for conditional validation or reusing validation logic.

The function accepts an optional parameter of type [Options] struct, which allows you to specify options such as the specific locale code and locale to use, and a custom JSON marshaler for errors.

The following example conditionally adds a Validator rule for the month_day value.

month := 5
monthDay := 11

val := v.New()

if month == 6 {
  val.Is(v.Number(monthDay, "month_day").LessOrEqualTo(10))
}

if val.Valid() {
  fmt.Println("The validation passes")
}

output:

The validation passes

As we mentioned above, you can pass the Options type to the New() function, in order to specify additional options when creating a new Validation session, such as the specific locale code and locale to use, and a custom JSON marshaler for errors. More information about the Options parameter in the following sections.

Error handling functions

Valgo provides three functions for handling validation errors:

ToError() function

The ToError() function returns the same value as ToValgoError() but as a standard Go error interface. This function is ideal for idiomatic error handling and integration with Go's native error system.

val := v.Is(v.String("", "name").Not().Blank())

if err := val.ToError(); err != nil {
    log.Printf("Validation failed: %v", err)
    return err
}
ToValgoError() function

The ToValgoError() function returns the same value as ToError() but as a concrete *valgo.Error type instead of the standard error interface. It's essentially a shortcut to ToError().(*valgo.Error), providing access to rich, structured error details.

val := v.Is(v.String("", "name").Not().Blank())

if errInfo := val.ToValgoError(); errInfo != nil {
    for field, valueError := range errInfo.Errors() {
        fmt.Printf("Field '%s': %v\n", field, valueError.Messages())
    }
}
Error() function (Deprecated)

The Error() function is deprecated in favor of ToError() or ToValgoError(). The Error() function name conflicts with Go's error interface implementation convention, where Error() typically implements the error interface for a type. This function will be removed when Valgo reaches version 1.

// DEPRECATED: Use ToError() or ToValgoError() instead
val := v.Is(v.String("", "name").Not().Blank())
if !val.Valid() {
    out, _ := json.MarshalIndent(val.Error(), "", "  ")
    fmt.Println(string(out))
}
When to use each function
  • Use ToError() for standard error handling and integration with Go's error system
  • Use ToValgoError() when you need detailed validation information, per-field messages, or custom error processing
  • Avoid Error() as it's deprecated and may be removed when Valgo reaches version 1
Custom JSON marshaling

All three functions support custom JSON marshaling functions:

customFunc := func(e *Error) ([]byte, error) {
    return []byte(`{"custom": "error"}`), nil
}

// Using custom marshaling with any of the functions
err := val.ToError(customFunc)
errInfo := val.ToValgoError(customFunc)
Additional JSON marshaling methods

Valgo provides additional JSON marshaling methods for enhanced error output:

MarshalJSONIndent() function

The MarshalJSONIndent() function provides custom JSON indentation for error output:

val := v.Is(v.String("", "name").Not().Blank())

if err := val.ToValgoError(); err != nil {
    jsonData, _ := err.MarshalJSONIndent("  ", "  ")
    fmt.Println(string(jsonData))
}
MarshalJSONPretty() function

The MarshalJSONPretty() function provides pretty-printed JSON output for better readability:

val := v.Is(v.String("", "name").Not().Blank())

if err := val.ToValgoError(); err != nil {
    jsonData, _ := err.MarshalJSONPretty()
    fmt.Println(string(jsonData))
}

Custom error message template

Customizing the default Valgo error messages is possible through the New() function as it's explained in the Localizing a validation session with New section, however the Valgo validators allow to customize the template of a specific template validator rule. Below is an example illustrating this with the String empty validator rule.

val := v.Is(v.String("", "address_field", "Address").Not().Empty("{{title}} must not be empty. Please provide the value in the input {{name}}."))

out, _ := json.MarshalIndent(val.ToError(), "", "  ")
fmt.Println(string(out))

output:

{
  "address": [
         "Address must not be empty. Please provide the value in the input address_field."
  ]
}

Localizing a validation session with New(...options) function

Valgo has localized error messages. The error messages are currently available in English (default), Spanish, German and Hungarian. However, it is possible to set error messages for any locale by passing the Options parameter to the New() function. Using this parameter, you can also customize the existing Valgo locale messages.

There are two options for localization: localeCode and locale. Below, we list the different ways to customize localization with these two parameters.

  • Changing the validation session's locale In the following example, we are setting the Spanish locale:

    // Creating the new validation session with other locale
    val := v.New(v.Options{ LocaleCode: "es" })
    
    // Testing the output
    val := val.Check(v.String(" ", "nombre").Not().Blank())
    
    out, _ := json.MarshalIndent(val.ToError(), "", "  ")
    fmt.Println(string(out))
    

    output:

    {
      "name": [
        "Nombre no puede estar en blanco"
      ]
    }
    

    If the specified locale does not exist, Valgo's default English locale will be used. If you wish to change the default locale, you should use a Factory function, which is explained in the Factory section.

  • Changing the locale entries In the example below, we are changing the entry for the "Not Blank" error. Since we are not specifying the localeCode, we are using and replacing the default English locale. However, you can also specify another localeCode if necessary.

    // Creating a new validation session and changing a locale entry
    val := v.New(v.Options{
      Locale: &Locale{
      	  ErrorKeyNotBlank: "{{title}} should not be blank",
        }
    })
    
    // Testing the output
    val := val.Check(v.String(" ", "name").Not().Blank())
    
    out, _ := json.MarshalIndent(val.ToError(), "", "  ")
    fmt.Println(string(out))
    

    output:

    {
      "name": [
        "Name should not be blank"
      ]
    }
    
  • Adding a new locale As mentioned previously, Valgo currently only has the English, Spanish, German and Hungarian locales, but we hope to have more soon. However, you can add your own custom locale. Below is an example using the Estonian language:

    // Creating a new validation session and adding a new locale with two entries
    val := v.New(v.Options{
      LocaleCode: "ee",
      Locale: &Locale{
      	  ErrorKeyNotBlank: "{{title}} ei tohi olla tühi",
        ErrorKeyNotFalse: "{{title}} ei tohi olla vale",
        }
    })
    
    // Testing the output
    val := val.Is(
      v.String(" ", "name").Not().Blank(),
      v.Bool(false, "active").Not().False(),
    )
    
    out, _ := json.MarshalIndent(val.ToError(), "", "  ")
    fmt.Println(string(out))
    

    output:

    {
      "name": [
        "Name ei tohi olla tühi"
      ],
      "active": [
        "Active ei tohi olla vale"
      ]
    }
    

    For entries not specified in the custom locale, the default Valgo locale (English) will be used. If you wish to change the default locale, you can use the Factory function, which is further explained in the Factory section.

We welcome pull requests for adding new locale messages, but please ensure that the translations are of high quality.

Managing common options with Factory

Valgo provides the Factory() function which allows you to create a valgo factory. With a valgo factory, you can create Validation sessions with preset options, avoiding having to pass options each time when a Validation is created. This allows more flexibility and easier management of options when creating Validation sessions.

The Factory function takes a parameter of type FactoryOptions struct, which allows you to modify the default locale code, add new locales, and set a custom JSON marshaler for errors. The ValidationFactory instance created by this function has all the functions to create Validations available in the package level (Is(), In(), Check(), New()) which creates a new Validation session with the preset options in the factory.

In the following example, we create a Factory with the default locale code set to Spanish, a new locale added for Estonian. This factory instance enables us to create validation sessions.

factory := v.Factory(v.FactoryOptions{
  LocaleCodeDefault: "es",
  Locales: map[string]*Locale{
      "ee": {
          v.ErrorKeyNotBlank: "{{title}} ei tohi olla tühi",
          v.ErrorKeyNotFalse: "{{title}} ei tohi olla vale",
      },
  }
})

// Error will contain the spanish error "Nombre no puede estar en blanco"
v1 := factory.Is(String(" ", "nombre").NotBlank())

// Error will contain the spanish error "Nime ei tohi olla tühi"
v2 := factory.New(Options{LocaleCode: "ee"}).Is(String(" ", "nime").Not().Blank())

Custom errors JSON output with Factory

It is possible to use the MarshalJsonFunc parameter of Factory for customizing the JSON output for errors.

customMarshalJson := func(e *Error) ([]byte, error) {

  errors := map[string]interface{}{}

  for k, v := range e.errors {
    errors[k] = v.Messages()
  }

  // Add a root key level called errors, which is not set by default in the Valgo implementation.
  return json.Marshal(map[string]map[string]interface{}{"errors": errors})
}

// Set the custom Marshal JSON function
factory := v.Factory(v.FactoryOptions{
  MarshalJsonFunc: customMarshalJson
})

// Now validate something to check if the output JSON contains the errors root key

val := factory.Is(v.String("", "name").Not().Empty())

out, _ := json.MarshalIndent(val.ToError(), "", "  ")
fmt.Println(string(out))

output:

{
  "errors": {
    "name": [
      "Name can't be empty"
    ]
  }
}

Validators

Validators establish the rules for validating a value. The validators are passed to a Validation session.

For each primitive Golang value type, Valgo provides a Validator. A Validator has different functions that set its value's validation rules.

Although Valgo has multiple types of validators, it can be extended with custom validators. Check the section Extending Valgo with Custom Validators for more information.

Validator value's name and title.

Validators only require the value to be validated, so, for example, the following code validates a string value by checking if it is empty.

val := v.New(v.String("").Empty())

val.ToError() output:

{
  "value_0": [
	  "Value 0 can't be empty",
  ]
}

In the example above, since we didn't specify a name for the value, Valgo generates a value_0 name and consequently the Value 0 title in the error message.

However, Validators allow you, optionally, to specify the value's name and title, as shown below:

Validator with value's name:

val := v.New(v.String("", "company_name").Not().Empty())

val.ToError() output:

{
  "company_name": [
	  "Company name can't be empty",
  ]
}

Validator with value's name and title:

val := v.New(v.String("", "company_name", "Customer").Not().Empty())

val.ToError() output:

{
  "company_name": [
	  "Customer can't be empty",
  ]
}

Not() validator function

Valgo validators have a Not() function to invert the boolean value associated with the next validator rule function.

In the following example, the call to Valid() will return false because Not() inverts the boolean value associated with the Zero() function.

valid := Is(v.Number(0).Not().Zero()).Valid()

fmt.Println(valid)

output:

false

String validator

The ValidatorString provides functions for setting validation rules for a string type value, or a custom type based on a string.

Below is a valid example for every String validator rule.

v.Is(v.String("Dennis Ritchie").EqualTo("Dennis Ritchie"))
v.Is(v.String("Steve Jobs").GreaterThan("Bill Gates"))
v.Is(v.String("Steve Jobs").GreaterOrEqualTo("Elon Musk"))
v.Is(v.String("C#").LessThan("Go"))
v.Is(v.String("Go").LessOrEqualTo("Golang"))
v.Is(v.String("Rust").Between("Go", "Typescript")) // Inclusive
v.Is(v.String("").Empty())
v.Is(v.String(" ").Blank())
v.Is(v.String("Dart").Passing(func(val string) bool { return val == "Dart" }))
v.Is(v.String("processing").InSlice([]string{"idle", "processing", "ready"}))

// Byte-length based
v.Is(v.String("123456").MaxBytes(6))
v.Is(v.String("123").MinBytes(3))
v.Is(v.String("1234").OfByteLength(4))
v.Is(v.String("12345").OfByteLengthBetween(4,6)) // Inclusive

// Rune-length based (unicode code points, tends to matter for languages that use non-Latin alphabet)
// 虎視眈々 is 4 runes/characters, but len(x) = 12 bytes
v.Is(v.String("虎視眈々").MaxLength(4))
v.Is(v.String("虎視眈々").MinLength(4))
v.Is(v.String("虎視眈々").OfLength(4))
v.Is(v.String("虎視眈々").OfLengthBetween(2,4)) // Inclusive

regex, _ := regexp.Compile("pre-.+"); v.Is(String("pre-approved").MatchingTo(regex))

String pointer validator

The ValidatorStringP provides functions for setting validation rules for a string type pointer, or a custom type based on a string pointer.

Below is a valid example for every String pointer validator rule.

x := "Dennis Ritchie"; v.Is(v.StringP(&x).EqualTo("Dennis Ritchie"))
x := "Steve Jobs";     v.Is(v.StringP(&x).GreaterThan("Bill Gates"))
x := "Steve Jobs";     v.Is(v.StringP(&x).GreaterOrEqualTo("Elon Musk"))
x := "C#";             v.Is(v.StringP(&x).LessThan("Go"))
x := "Go";             v.Is(v.StringP(&x).LessOrEqualTo("Golang"))
x := "Rust";           v.Is(v.StringP(&x).Between("Go", "Typescript")) // Inclusive
x := "";               v.Is(v.StringP(&x).Empty())
x := " ";              v.Is(v.StringP(&x).Blank())
x := "Dart";           v.Is(v.StringP(&x).Passing(func(val *string) bool { return *val == "Dart" }))
x := "processing";     v.Is(v.StringP(&x).InSlice([]string{"idle", "processing", "ready"}))

// Byte-length based
x := "123456";         v.Is(v.StringP(&x).MaxBytes(6))
x := "123";            v.Is(v.StringP(&x).MinBytes(3))
x := "1234";           v.Is(v.StringP(&x).OfByteLength(4))
x := "12345";          v.Is(v.StringP(&x).OfByteLengthBetween(4,6)) // Inclusive

// Rune-length based (counts characters instead of bytes)
// 虎視眈々 is 4 runes/characters, but len(x) = 12 bytes
x := "虎視眈々";      v.Is(v.StringP(&x).MaxLength(4))
x := "虎視眈々";      v.Is(v.StringP(&x).MinLength(4))
x := "虎視眈々";      v.Is(v.StringP(&x).OfLength(4))
x := "虎視眈々";      v.Is(v.StringP(&x).OfLengthBetween(2,4)) // Inclusive

x := "pre-approved"; regex, _ := regexp.Compile("pre-.+"); v.Is(StringP(&x).MatchingTo(regex))
x := "";               v.Is(v.StringP(&x).EmptyOrNil())
x := " ";              v.Is(v.StringP(&x).BlankOrNil())
var x *string;         v.Is(v.StringP(x).Nil())

Number validator

The Number validator provides functions for setting validation rules for a TypeNumber value, or a custom type based on a TypeNumber.

TypeNumber is a generic interface defined by Valgo that generalizes any standard Golang type. Below is Valgo's definition of TypeNumber:

type TypeNumber interface {
  ~int |
  ~int8 |
  ~int16 |
  ~int32 |
  ~int64 |
  ~uint |
  ~uint8 |
  ~uint16 |
  ~uint32 |
  ~uint64 |
  ~float32 |
  ~float64
}

Below is a valid example for every Number validator rule.

v.Is(v.Number(10).EqualTo(10))
v.Is(v.Number(11).GreaterThan(10))
v.Is(v.Number(10).GreaterOrEqualTo(10))
v.Is(v.Number(10).LessThan(11))
v.Is(v.Number(10).LessOrEqualTo(10))
v.Is(v.Number(11).Between(10, 12)) // Inclusive
v.Is(v.Number(0).Zero())
v.Is(v.Number(10).Passing(func(val int) bool { return val == 10 }))
v.Is(v.Number(20).InSlice([]int{10, 20, 30}))

Number pointer validator

The Number pointer validator provides functions for setting validation rules for a TypeNumber pointer, or a custom type based on a TypeNumber pointer.

As it's explained in Number validator, the TypeNumber is a generic interface defined by Valgo that generalizes any standard Golang type.

Below is a valid example for every Number pointer validator rule.

x := 10;    v.Is(v.NumberP(&x).EqualTo(10))
x := 11;    v.Is(v.NumberP(&x).GreaterThan(10))
x := 10;    v.Is(v.NumberP(&x).GreaterOrEqualTo(10))
x := 10;    v.Is(v.NumberP(&x).LessThan(11))
x := 10;    v.Is(v.NumberP(&x).LessOrEqualTo(10))
x := 11;    v.Is(v.NumberP(&x).Between(10, 12)) // Inclusive
x := 0;     v.Is(v.NumberP(&x).Zero())
x := 10;    v.Is(v.NumberP(&x).Passing(func(val *int) bool { return *val == 10 }))
x := 20;    v.Is(v.NumberP(&x).InSlice([]int{10, 20, 30}))
x := 0;     v.Is(v.NumberP(&x).ZeroOrNil())
var x *int; v.Is(v.NumberP(x).Nil())

Int validators

The ValidatorInt[T] provides functions for setting validation rules for int, int8, int16, int32, int64, and rune types, or custom types based on them.

Below is a valid example for every Int validator rule.

// Basic numeric validations
age := int(25)
v.Is(v.Int(age).EqualTo(25))
v.Is(v.Int(age).GreaterThan(18))
v.Is(v.Int(age).LessThan(65))
v.Is(v.Int(age).Between(18, 65))

// Zero, positive, and negative validations
v.Is(v.Int(0).Zero())
v.Is(v.Int(5).Positive())
v.Is(v.Int(-3).Negative())

// Custom validation and slice checking
v.Is(v.Int(age).Passing(func(a int) bool { return a >= 18 }))
v.Is(v.Int(age).InSlice([]int{18, 25, 30, 35}))

// Works with all int variants
v.Is(v.Int8(int8(10)).GreaterThan(int8(5)))
v.Is(v.Int16(int16(100)).LessThan(int16(200)))
v.Is(v.Int32(int32(1000)).Between(int32(500), int32(1500)))
v.Is(v.Int64(int64(10000)).EqualTo(int64(10000)))
v.Is(v.Rune('A').EqualTo('A'))

// Works with custom int types
type UserID int
userID := UserID(123)
v.Is(v.Int(userID).GreaterThan(UserID(0)))

Int pointer validator

The ValidatorIntP[T] provides functions for setting validation rules for int, int8, int16, int32, int64, and rune pointer types, or custom types based on them.

Below is a valid example for every Int pointer validator rule.

// Basic numeric validations
age := int(25)
v.Is(v.IntP(&age).EqualTo(25))
v.Is(v.IntP(&age).GreaterThan(18))
v.Is(v.IntP(&age).LessThan(65))
v.Is(v.IntP(&age).Between(18, 65))

// Zero, positive, and negative validations
zero := int(0)
positive := int(5)
negative := int(-3)
v.Is(v.IntP(&zero).Zero())
v.Is(v.IntP(&positive).Positive())
v.Is(v.IntP(&negative).Negative())

// Custom validation and slice checking
v.Is(v.IntP(&age).Passing(func(a *int) bool { return *a >= 18 }))
v.Is(v.IntP(&age).InSlice([]int{18, 25, 30, 35}))

// Nil and zero-or-nil validations
var nilInt *int
v.Is(v.IntP(nilInt).Nil())

zeroInt := int(0)
v.Is(v.IntP(&zeroInt).ZeroOrNil())

// Works with all int variants
int8Val := int8(10)
v.Is(v.Int8P(&int8Val).GreaterThan(int8(5)))

int16Val := int16(100)
v.Is(v.Int16P(&int16Val).LessThan(int16(200)))

int32Val := int32(1000)
v.Is(v.Int32P(&int32Val).Between(int32(500), int32(1500)))

int64Val := int64(10000)
v.Is(v.Int64P(&int64Val).EqualTo(int64(10000)))

runeVal := rune('A')
v.Is(v.RuneP(&runeVal).EqualTo('A'))

// Works with custom int pointer types
type UserID int
userID := UserID(123)
v.Is(v.IntP(&userID).GreaterThan(UserID(0)))

Uint validators

The ValidatorUint[T] provides functions for setting validation rules for uint, uint8, uint16, uint32, uint64, and byte types, or custom types based on them.

Below is a valid example for every Uint validator rule.

// Basic numeric validations
count := uint(10)
v.Is(v.Uint(count).EqualTo(10))
v.Is(v.Uint(count).GreaterThan(5))
v.Is(v.Uint(count).LessThan(20))
v.Is(v.Uint(count).Between(5, 20))

// Zero validation (uint values are always >= 0)
v.Is(v.Uint(0).Zero())

// Custom validation and slice checking
v.Is(v.Uint(count).Passing(func(c uint) bool { return c > 0 }))
v.Is(v.Uint(count).InSlice([]uint{5, 10, 15, 20}))

// Works with all uint variants
v.Is(v.Uint8(uint8(10)).GreaterThan(uint8(5)))
v.Is(v.Uint16(uint16(100)).LessThan(uint16(200)))
v.Is(v.Uint32(uint32(1000)).Between(uint32(500), uint32(1500)))
v.Is(v.Uint64(uint64(10000)).EqualTo(uint64(10000)))
v.Is(v.Byte(byte(65)).EqualTo(byte(65)))

// Works with custom uint types
type Count uint
count := Count(5)
v.Is(v.Uint(count).GreaterThan(Count(0)))

Uint pointer validator

The ValidatorUintP[T] provides functions for setting validation rules for uint, uint8, uint16, uint32, uint64, and byte pointer types, or custom types based on them.

Below is a valid example for every Uint pointer validator rule.

// Basic numeric validations
count := uint(10)
v.Is(v.UintP(&count).EqualTo(10))
v.Is(v.UintP(&count).GreaterThan(5))
v.Is(v.UintP(&count).LessThan(20))
v.Is(v.UintP(&count).Between(5, 20))

// Zero validation (uint values are always >= 0)
zero := uint(0)
v.Is(v.UintP(&zero).Zero())

// Custom validation and slice checking
v.Is(v.UintP(&count).Passing(func(c *uint) bool { return *c > 0 }))
v.Is(v.UintP(&count).InSlice([]uint{5, 10, 15, 20}))

// Nil and zero-or-nil validations
var nilUint *uint
v.Is(v.UintP(nilUint).Nil())

zeroUint := uint(0)
v.Is(v.UintP(&zeroUint).ZeroOrNil())

// Works with all uint variants
uint8Val := uint8(10)
v.Is(v.Uint8P(&uint8Val).GreaterThan(uint8(5)))

uint16Val := uint16(100)
v.Is(v.Uint16P(&uint16Val).LessThan(uint16(200)))

uint32Val := uint32(1000)
v.Is(v.Uint32P(&uint32Val).Between(uint32(500), uint32(1500)))

uint64Val := uint64(10000)
v.Is(v.Uint64P(&uint64Val).EqualTo(uint64(10000)))

byteVal := byte(65)
v.Is(v.ByteP(&byteVal).EqualTo(byte(65)))

// Works with custom uint pointer types
type Count uint
count := Count(5)
v.Is(v.UintP(&count).GreaterThan(Count(0)))

Float validators

The ValidatorFloat[T] provides functions for setting validation rules for float32 and float64 types, or custom types based on them.

Below is a valid example for every Float validator rule.

// Basic numeric validations
price := 19.99
v.Is(v.Float64(price).EqualTo(19.99))
v.Is(v.Float64(price).GreaterThan(10.0))
v.Is(v.Float64(price).LessThan(50.0))
v.Is(v.Float64(price).Between(10.0, 50.0))

// Zero, positive, and negative validations
v.Is(v.Float64(0.0).Zero())
v.Is(v.Float64(5.5).Positive())
v.Is(v.Float64(-3.14).Negative())

// Special float validations
v.Is(v.Float64(math.NaN()).NaN())
v.Is(v.Float64(math.Inf(1)).Infinite())
v.Is(v.Float64(3.14).Finite())

// Custom validation and slice checking
v.Is(v.Float64(price).Passing(func(p float64) bool { return p > 0 }))
v.Is(v.Float64(price).InSlice([]float64{9.99, 19.99, 29.99}))

// Work with Float32 variant
v.Is(v.Float32(float32(0.0)).Zero())
v.Is(v.Float32(float32(5.5)).Positive())
v.Is(v.Float32(float32(-3.14)).Negative())

// Works with custom float types
type Price float64
price := Price(29.99)
v.Is(v.Float64(price).GreaterThan(Price(20.0)))

Float pointer validator

The ValidatorFloatP[T] provides functions for setting validation rules for float32 and float64 pointer types, or custom types based on them.

Below is a valid example for every Float pointer validator rule.

// Basic numeric validations
price := 19.99
v.Is(v.Float64P(&price).EqualTo(19.99))
v.Is(v.Float64P(&price).GreaterThan(10.0))
v.Is(v.Float64P(&price).LessThan(50.0))
v.Is(v.Float64P(&price).Between(10.0, 50.0))

// Zero, positive, and negative validations
zero := 0.0
positive := 5.5
negative := -3.14
v.Is(v.Float64P(&zero).Zero())
v.Is(v.Float64P(&positive).Positive())
v.Is(v.Float64P(&negative).Negative())

// Special float validations
nan := math.NaN()
inf := math.Inf(1)
finite := 3.14
v.Is(v.Float64P(&nan).NaN())
v.Is(v.Float64P(&inf).Infinite())
v.Is(v.Float64P(&finite).Finite())

// Custom validation and slice checking
v.Is(v.Float64P(&price).Passing(func(p *float64) bool { return *p > 0 }))
v.Is(v.Float64P(&price).InSlice([]float64{9.99, 19.99, 29.99}))

// Nil and zero-or-nil validations
var nilFloat *float64
v.Is(v.Float64P(nilFloat).Nil())

zeroFloat := 0.0
v.Is(v.Float64P(&zeroFloat).ZeroOrNil())

// Works with all float variants
float32Val := float32(3.14)
v.Is(v.Float32P(&float32Val).Positive())

float64Val := 2.718
v.Is(v.Float64P(&float64Val).Positive())

// Works with custom float pointer types
type Price float64
price := Price(29.99)
v.Is(v.Float64P(&price).GreaterThan(Price(20.0)))

Bool validator

The Bool validator provides functions for setting validation rules for a bool type value, or a custom type based on a bool.

Below is a valid example for every Bool validator rule.

v.Is(v.Bool(true).EqualTo(true))
v.Is(v.Bool(true).True())
v.Is(v.Bool(false).False())
v.Is(v.Bool(true).Passing(func(val bool) bool { return val == true }))
v.Is(v.Bool(true).InSlice([]string{true, false}))

Boolean pointer validator

The Bool pointer validator provides functions for setting validation rules for a bool pointer, or a custom type based on a bool pointer.

Below is a valid example for every Bool pointer validator rule.

x := true;   v.Is(v.BoolP(&x).EqualTo(true))
x := true;   v.Is(v.BoolP(&x).True())
x := false;  v.Is(v.BoolP(&x).False())
x := true;   v.Is(v.BoolP(&x).Passing(func(val *bool) bool { return val == true }))
x := true;   v.Is(v.BoolP(&x).InSlice([]string{true, false}))
x := false;  v.Is(v.BoolP(&x).FalseOrNil())
var x *bool; v.Is(v.BoolP(x).Nil())

Time validator

The ValidatorTime provides functions for setting validation rules for a time.Time type value, or a custom type based on a time.Time.

Below is a valid example for every Time validator rule.

import "time"

v.Is(v.Time(time.Now()).EqualTo(time.Now()))
v.Is(v.Time(time.Now()).After(time.Now().Add(-time.Hour)))
v.Is(v.Time(time.Now()).AfterOrEqualTo(time.Now().Add(-time.Hour)))
v.Is(v.Time(time.Now()).Before(time.Now().Add(time.Hour)))
v.Is(v.Time(time.Now()).BeforeOrEqualTo(time.Now().Add(time.Hour)))
v.Is(v.Time(time.Now()).Between(time.Now().Add(-time.Hour), time.Now().Add(2*time.Hour))) // Inclusive
v.Is(v.Time(time.Time{}).Zero())
v.Is(v.Time(time.Now()).Passing(func(val time.Time) bool { return val.Before(time.Now().Add(2*time.Hour)) }))
v.Is(v.Time(time.Now()).InSlice([]time.Time{time.Now(), time.Now().Add(time.Hour)}))

Time pointer validator

The ValidatorTimeP provides functions for setting validation rules for a time.Time type pointer, or a custom type based on a time.Time pointer.

Below is a valid example for every Time pointer validator rule.

import "time"

x := time.Now(); v.Is(v.TimeP(&x).EqualTo(time.Now()))
x = time.Now(); v.Is(v.TimeP(&x).After(time.Now().Add(-time.Hour)))
x = time.Now(); v.Is(v.TimeP(&x).AfterOrEqualTo(time.Now().Add(-time.Hour)))
x = time.Now(); v.Is(v.TimeP(&x).Before(time.Now().Add(time.Hour)))
x = time.Now(); v.Is(v.TimeP(&x).BeforeOrEqualTo(time.Now().Add(time.Hour)))
x = time.Now(); v.Is(v.TimeP(&x).Between(time.Now().Add(-time.Hour), time.Now().Add(2*time.Hour))) // Inclusive
x = time.Time{}; v.Is(v.TimeP(&x).Zero())
x = time.Now(); v.Is(v.TimeP(&x).Passing(func(val *time.Time) bool { return val.Before(time.Now().Add(2*time.Hour)) }))
x = time.Now(); v.Is(v.TimeP(&x).InSlice([]time.Time{time.Now(), time.Now().Add(time.Hour)}))
var x *time.Time; v.Is(v.TimeP(x).Nil())
x = new(time.Time); v.Is(v.TimeP(x).NilOrZero())

Comparable validator

The ValidatorComparable[T] provides functions for setting validation rules for any Go type that implements the Go comparable constraint. This validator is optimized for equality comparisons and slice operations with compile-time type safety.

Below is a valid example for every Comparable validator rule.

// Basic equality comparison
status := "running"
v.Is(v.Comparable(status).EqualTo("running"))

// Custom validation function with type safety
type Status string
status := Status("running")
v.Is(v.Comparable(status).Passing(func(s Status) bool {
    return s == "running" || s == "paused"
}))

// Check if value exists in a slice
status := "idle"
validStatuses := []string{"idle", "paused", "stopped"}
v.Is(v.Comparable(status).InSlice(validStatuses))

// Works with custom comparable types
type User struct {
  ID int
}
userA := User{ID: 123}
userB := User{ID: 123}
v.Is(v.Comparable(userA).EqualTo(userB))

Comparable pointer validator

The ValidatorComparableP[T] provides functions for setting validation rules for any Go type pointer that implements the comparable constraint. This validator is optimized for equality comparisons and slice operations with compile-time type safety.

Below is a valid example for every Comparable pointer validator rule.

// Basic equality comparison
status := "running"
v.Is(v.ComparableP(&status).EqualTo("running"))

// Custom validation function with type safety
type Status string
status := Status("running")
v.Is(v.ComparableP(&status).Passing(func(s *Status) bool {
    return *s == "running" || *s == "paused"
}))

// Check if value exists in a slice
status := "idle"
validStatuses := []string{"idle", "paused", "stopped"}
v.Is(v.ComparableP(&status).InSlice(validStatuses))

// Nil validation
var nilStatus *string
v.Is(v.ComparableP(nilStatus).Nil())

// Works with custom comparable pointer types
type User struct {
    ID int
}
userA := &User{ID: 123}
userB := User{ID: 123}
v.Is(v.ComparableP(userA).EqualTo(userB))

Typed validator

The ValidatorTyped[T] provides functions for setting validation rules for any Go type with compile-time type safety. This is a type-safe alternative to the Any validator, addressing type safety concerns.

Below is a valid example for every Typed validator rule.

// Type-safe custom validation function
type Status string
status := Status("running")
v.Is(v.Typed(status).Passing(func(s Status) bool {
    return s == "running" || s == "paused"
}))

// Nil validation for pointer types
var s *string
v.Is(v.Typed(s).Nil())

// Works with any Go type
type User struct {
    Name string
    Age  int
}
user := User{"John", 30}
v.Is(v.Typed(user).Passing(func(u User) bool {
    return u.Age >= 18
}))

Any validator

With the Any validator, you can set validation rules for any value or pointer.

Below is a valid example of every Any validator rule.

v.Is(v.Any("svelte").Passing(func(val any) bool { return val == "svelte" }))
var x *bool; v.Is(v.Any(x).Nil())

EqualTo (DEPRECATED) any is not safely comparable. Do not use EqualTo on ValidatorAny; use EqualTo on ValidatorComparable instead. EqualTo on ValidatorAny will be removed in Valgo v1.0.0.

v.Is(v.Any("react").EqualTo("react"))

Custom type validators

All golang validators allow to pass a custom type based on its value type. Below some valid examples.

type Status string
var status Status = "up"
val := v.Is(v.String(status).InSlice([]Status{"down", "up", "paused"}))

type Level int
var level Level = 1
val = v.Is(v.Int(level).LessThan(Level(2)))

type Stage int64
var stage Stage = 2
val := v.Is(v.NumberP(&stage).GreaterThan(Stage(1)))

// Using the new type-safe validators
type UserID int
userID := UserID(123)
val = v.Is(v.Int(userID).GreaterThan(UserID(0)))

type Price float32
price := Price(19.99)
val = v.Is(v.Float32(price).Positive())

type Status string
status := Status("running")
val = v.Is(v.Comparable(status).EqualTo(Status("running")))

Or Operator in Validators

The Or operator function enables developers to combine validator rules using a logical OR chain. This addition allows for more nuanced validator scenarios, where a value may satisfy one of multiple conditions to be considered valid.

Overview

In Valgo, validator rules are typically chained together using an implicit AND logic. This means that for a value to be deemed valid, it must satisfy all specified conditions. The Or operator provides an alternative by allowing conditions to be linked with OR logic. In such cases, a value is considered valid if it meets at least one of the chained conditions.

The Or operator follows a simple left-to-right boolean priority, akin to the Go language's approach to evaluating boolean expressions. Valgo does not have an equivalent to parentheses in API functions, in order to keep the syntax simple and readable. We believe that complex boolean logic becomes harder to read with a Fluent API interface, so for those cases, it is preferred to use imperative Go programming language constructs.

Usage

To utilize the Or operator, simply insert .Or(). between two conditions within your validator chain. Here's a basic example:

v := Is(Bool(true).True().Or().False())

In this case, the validator passes because the boolean value true satisfies the first condition before the Or() operator.

Key Points

  • Implicit AND Logic: By default, when validators are chained without specifying the Or() operator, they are combined using an AND logic. Each condition must be met for the validation to pass.
  • No Short-circuiting for Check: Unlike the Is function, which evaluates conditions lazily and may short-circuit (stop evaluating once the overall outcome is determined), the Check function ensures that all conditions are evaluated, regardless of their order and the use of Or.

Examples

Below are examples demonstrating different scenarios using the Or operator, including combinations with the Not operator and multiple Or conditions in sequence. These examples illustrate how you can tailor complex validation logic to suit your needs.

// Validation with two valid OR conditions
v = Is(Bool(true).True().Or().True())
assert.True(t, v.Valid())

// Validation with a valid OR condition followed by an invalid AND condition
v = Is(Bool(true).False().Or().True().False())
assert.False(t, v.Valid())

// Validation combining NOT and OR operators
v = Is(Bool(true).Not().False().Or().False())
assert.True(t, v.Valid())

These examples are intended to provide a clear understanding of how to effectively use the Or operator in your validations. By leveraging this functionality, you can create more flexible and powerful validation rules, enhancing the robustness and usability of your applications.

Extending Valgo with custom validators

While all validators in Golang provide a Passing(...) function, which allows you to use a custom validator function, Valgo also allows you to create your own validator.

With this functionality Valgo can be extended with Validator libraries, which we encourage the community to do.

For example, let's say we want to create a validation for the following ID struct, where a user must provide at least one property.

The struct to validate:

// Type to validate
type ID struct {
  Phone string
  Email string
}

the custom validator code:

// The custom validator type
type ValidatorID struct {
	context *valgo.ValidatorContext
}

// The custom validator implementation of `valgo.Validator`
func (validator *ValidatorID) Context() *valgo.ValidatorContext {
	return validator.context
}

// Here is the function that passes the value to the custom validator
func IDValue(value ID, nameAndTitle ...string) *ValidatorID {
	return &ValidatorID{context: valgo.NewContext(value, nameAndTitle...)}
}

// The Empty rule implementation
func (validator *ValidatorID) Empty(template ...string) *ValidatorID {
	validator.context.Add(
		func() bool {
			return len(strings.Trim(validator.context.Value().(ID).Phone, " ")) == 0 &&
				len(strings.Trim(validator.context.Value().(ID).Email, " ")) == 0
		},
		v.ErrorKeyEmpty, template...)

	return validator
}

// It would be possible to create a rule NotEmpty() instead of Empty(), but if you add a Not() function then your validator will be more flexible.

func (validator *ValidatorID) Not() *ValidatorID {
	validator.context.Not()

	return validator
}

using our validator:

val := v.Is(IDValue(ID{}, "id").Not().Empty())

out, _ := json.MarshalIndent(val.ToError(), "", "  ")
fmt.Println(string(out))

output:

{
  "identification": [
	  "Id can't be empty"
  ]
}

List of rules by validator type

  • String validator

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Empty
    • Blank
    • Passing
    • InSlice
    • MatchingTo
    • MaxBytes
    • MinBytes
    • OfByteLength
    • OfByteLengthBetween
    • MaxLength
    • MinLength
    • OfLength
    • OfLengthBetween
  • StringP validator - for string pointer

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Empty
    • Blank
    • Passing
    • InSlice
    • MatchingTo
    • MaxBytes
    • MinBytes
    • OfByteLength
    • OfByteLengthBetween
    • MaxLength
    • MinLength
    • OfLength
    • OfLengthBetween
    • BlankOrNil
    • EmptyOrNil
    • Nil
  • Bool validator

    • EqualTo
    • Passing
    • True
    • False
    • InSlice
  • BoolP validator - for boolean pointer

    • EqualTo
    • Passing
    • True
    • False
    • InSlice
    • FalseOrNil
    • Nil
  • Number - for number types Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Float32, Float64, Byte, Rune

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • InSlice
    • Passing
  • NumberP - for number pointer IntP, Int8P, Int16P, Int32P, Int64P, UintP, Uint8P, Uint16P, Uint32P, Uint64P, Float32P, Float64P, ByteP, RuneP

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • InSlice
    • Passing
    • ZeroOrNil
    • Nil
  • Time validator

    • EqualTo
    • After
    • AfterOrEqualTo
    • Before
    • BeforeOrEqualTo
    • Between
    • Zero
    • Passing
    • InSlice
  • TimeP validator - for time.Time pointer

    • EqualTo
    • After
    • AfterOrEqualTo
    • Before
    • BeforeOrEqualTo
    • Between
    • Zero
    • Passing
    • InSlice
    • Nil
    • NilOrZero
  • Any validator

    • EqualTo (Deprecated)
    • Passing
    • Nil
  • Comparable validator - for comparable types

    • EqualTo
    • Passing
    • InSlice
  • ComparableP validator - for comparable pointer types

    • EqualTo
    • Passing
    • InSlice
    • Nil
  • Typed validator - for any Go type with type safety

    • Passing
    • Nil
  • Float validator - for float32 and float64 types

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • Positive
    • Negative
    • Passing
    • InSlice
    • NaN
    • Infinite
    • Finite
  • FloatP validator - for float32 and float64 pointer types

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • Positive
    • Negative
    • Passing
    • InSlice
    • NaN
    • Infinite
    • Finite
    • ZeroOrNil
    • Nil
  • Int validator - for int, int8, int16, int32, int64, and rune types

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • Positive
    • Negative
    • Passing
    • InSlice
  • IntP validator - for int, int8, int16, int32, int64, and rune pointer types

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • Positive
    • Negative
    • Passing
    • InSlice
    • ZeroOrNil
    • Nil
  • Uint validator - for uint, uint8, uint16, uint32, uint64, and byte types

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • Passing
    • InSlice
  • UintP validator - for uint, uint8, uint16, uint32, uint64, and byte pointer types

    • EqualTo
    • GreaterThan
    • GreaterOrEqualTo
    • LessThan
    • LessOrEqualTo
    • Between
    • Zero
    • Passing
    • InSlice
    • ZeroOrNil
    • Nil

Github Code Contribution Guide

We welcome contributions to our project! To make the process smooth and efficient, please follow these guidelines when submitting code:

  • Discuss changes with the community: We encourage contributors to discuss their proposed changes or improvements with the community before starting to code. This ensures that the changes align with the focus and purpose of the project, and that other contributors are aware of the work being done.

  • Make commits small and cohesive: It is important to keep your commits focused on a single task or change. This makes it easier to review and understand your changes.

  • Check code formatting with go fmt: Before submitting your code, please ensure that it is properly formatted using the go fmt command.

  • Make tests to cover your changes: Please include tests that cover the changes you have made. This ensures that your code is functional and reduces the likelihood of bugs.

  • Update golang docs and README to cover your changes: If you have made changes that affect documentation or the README file, please update them accordingly.

  • Keep a respectful language with a collaborative tune: We value a positive and collaborative community. Please use respectful language when communicating with other contributors or maintainers.

License

Copyright © 2025 Carlos Forero

Valgo is released under the MIT License

Documentation

Overview

Valgo is a type-safe, expressive, and extensible validator library for Golang. Valgo is built with generics, so Go 1.18 or higher is required.

Valgo differs from other Golang validation libraries in that the rules are written in functions and not in struct tags. This allows greater flexibility and freedom when it comes to where and how data is validated.

Additionally, Valgo supports customizing and localizing validation messages.

Example
val := Is(String("Bob", "full_name").Not().Blank().OfLengthBetween(4, 20)).
	Is(Number(17, "age").GreaterThan(18))

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "age": [
    "Age must be greater than \"18\""
  ],
  "full_name": [
    "Full name must have a length between \"4\" and \"20\""
  ]
}

Index

Examples

Constants

View Source
const (
	ErrorKeyAfter    = "after"
	ErrorKeyNotAfter = "not_after"

	ErrorKeyAfterOrEqualTo    = "after_equal_to"
	ErrorKeyNotAfterOrEqualTo = "not_after_equal_to"

	ErrorKeyBefore    = "before"
	ErrorKeyNotBefore = "not_before"

	ErrorKeyBeforeOrEqualTo    = "before_equal_to"
	ErrorKeyNotBeforeOrEqualTo = "not_before_equal_to"

	ErrorKeyBetween    = "between"
	ErrorKeyNotBetween = "not_between"

	ErrorKeyBlank    = "blank"
	ErrorKeyNotBlank = "not_blank"

	ErrorKeyEmpty    = "empty"
	ErrorKeyNotEmpty = "not_empty"

	ErrorKeyEqualTo    = "equal_to"
	ErrorKeyNotEqualTo = "not_equal_to"

	ErrorKeyFalse    = "false"
	ErrorKeyNotFalse = "not_false"

	ErrorKeyGreaterOrEqualTo    = "greater_equal_to"
	ErrorKeyNotGreaterOrEqualTo = "not_greater_equal_to"

	ErrorKeyGreaterThan    = "greater_than"
	ErrorKeyNotGreaterThan = "not_greater_than"

	ErrorKeyInSlice    = "in_slice"
	ErrorKeyNotInSlice = "not_in_slice"

	ErrorKeyLength    = "length"
	ErrorKeyNotLength = "not_length"

	ErrorKeyLengthBetween    = "length_between"
	ErrorKeyNotLengthBetween = "not_length_between"

	ErrorKeyLessOrEqualTo    = "less_or_equal_to"
	ErrorKeyNotLessOrEqualTo = "not_less_or_equal_to"

	ErrorKeyLessThan    = "less_than"
	ErrorKeyNotLessThan = "not_less_than"

	ErrorKeyMatchingTo    = "matching_to"
	ErrorKeyNotMatchingTo = "not_matching_to"

	ErrorKeyMaxLength    = "max_length"
	ErrorKeyNotMaxLength = "not_max_length"

	ErrorKeyMinLength    = "min_length"
	ErrorKeyNotMinLength = "not_min_length"

	ErrorKeyNil    = "nil"
	ErrorKeyNotNil = "not_nil"

	ErrorKeyPassing    = "passing"
	ErrorKeyNotPassing = "not_passing"

	ErrorKeyTrue    = "true"
	ErrorKeyNotTrue = "not_true"

	ErrorKeyZero    = "zero"
	ErrorKeyNotZero = "not_zero"

	ErrorKeyPositive    = "positive"
	ErrorKeyNotPositive = "not_positive"

	ErrorKeyNegative    = "negative"
	ErrorKeyNotNegative = "not_negative"

	ErrorKeyZeroOrNil    = "zero_or_nil"
	ErrorKeyNotZeroOrNil = "not_zero_or_nil"

	ErrorKeyPositiveOrNil    = "positive_or_nil"
	ErrorKeyNotPositiveOrNil = "not_positive_or_nil"

	ErrorKeyNegativeOrNil    = "negative_or_nil"
	ErrorKeyNotNegativeOrNil = "not_negative_or_nil"

	ErrorKeyNaN    = "nan"
	ErrorKeyNotNaN = "not_nan"

	ErrorKeyInfinite    = "infinite"
	ErrorKeyNotInfinite = "not_infinite"

	ErrorKeyFinite    = "finite"
	ErrorKeyNotFinite = "not_finite"
)
View Source
const (
	LocaleCodeEn = "en"
	LocaleCodeEs = "es"
	LocaleCodeDe = "de"
	LocaleCodeHu = "hu"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	// contains filtered or unexported fields
}

Implementation of the Go error interface in Valgo. The [Validation.Error()] method returns a value of this type.

There is a function in this type, [Errors()], that returns a list of errors in a Validation session.

func (*Error) Error

func (e *Error) Error() string

Return the error message associated with a Valgo error.

func (*Error) Errors

func (e *Error) Errors() map[string]*valueError

Return a map with each Invalid value error.

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

Returns the JSON encoding of the validation error messages.

A custom function can be set either by passing it as a parameter to [validation.Error()] or through FactoryOptions.

func (*Error) MarshalJSONIndent added in v0.7.0

func (e *Error) MarshalJSONIndent(prefix, indent string) ([]byte, error)

Returns the JSON encoding of the validation error messages with the given prefix and indent.

This function does not call a custom marshalJsonFunc function if it is set.

func (*Error) MarshalJSONPretty added in v0.7.0

func (e *Error) MarshalJSONPretty() ([]byte, error)

Returns the JSON encoding of the validation error messages with the pretty format.

This is a shortcut for MarshalJSONIndent("", " "). It does not call a custom marshalJSONFunc function if it is set.

type FactoryOptions added in v0.2.0

type FactoryOptions struct {
	// A string field that represents the default locale code to use by the
	// factory if a specific locale code is not provided when a Validation is
	// created
	LocaleCodeDefault string
	// A map field that allows to modify the current or add new locales
	Locales map[string]*Locale
	// A function field that allows to set a custom JSON marshaler for [Error]
	MarshalJsonFunc func(e *Error) ([]byte, error)
}

FactoryOptions is a struct in Go that is used to pass options to a [Factory()]

type Locale added in v0.2.0

type Locale map[string]string

Locale is a type alias that represents a map of locale entries. The keys in the map are strings that represent the entry's identifier, and the values are strings that contain the corresponding localized text for that entry

type Options added in v0.2.0

type Options struct {

	// A string field that represents the locale code to use by the [Validation]
	// session
	LocaleCode string
	// A map field that allows to modify or add a new [Locale]
	Locale *Locale
	// A function field that allows to set a custom JSON marshaler for [Error]
	MarshalJsonFunc func(e *Error) ([]byte, error)
	// contains filtered or unexported fields
}

type TypeNumber

type TypeNumber interface {
	~int |
		~int8 |
		~int16 |
		~int32 |
		~int64 |
		~uint |
		~uint8 |
		~uint16 |
		~uint32 |
		~uint64 |
		~float32 |
		~float64
}

Custom generic type covering all numeric types. This type is used as the value type in ValidatorNumber and ValidatorNumberP.

type Validation

type Validation struct {
	// contains filtered or unexported fields
}

The Validation session in Valgo is the main structure for validating one or more values. It is called Validation in code.

A Validation session will contain one or more Validators, where each Validator will have the responsibility to validate a value with one or more rules.

There are multiple functions to create a Validation session, depending on the requirements:

the function Is(...) is likely to be the most frequently used function in your validations. When Is(...) is called, the function creates a validation and receives a validator at the same time.

func AddErrorMessage

func AddErrorMessage(name string, message string) *Validation

Create a new Validation session and add an error message to it without executing a field validator. By adding this error message, the Validation session will be marked as invalid.

func Check

func Check(validators ...Validator) *Validation

The Check(...) function is similar to the Is(...) function, however with Check(...)` the Rules of the Validator parameter are not short-circuited, which means that regardless of whether a previous rule was valid, all rules are checked.

This example shows two rules that fail due to the empty value in the full_name Validator, and since the Validator is not short-circuited, both error messages are added to the error result.

Example
val := Check(String("", "full_name").Not().Blank().OfLengthBetween(4, 20))

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "full_name": [
    "Full name can't be blank",
    "Full name must have a length between \"4\" and \"20\""
  ]
}

func Do added in v0.7.0

func Do(function func(val *Validation)) *Validation

The Do(...) function executes the given function with the current Validation instance and returns the same instance.

See Validation.Do(...) for more information.

Example
mustBeAdmin := true
val := Is(String("", "username").Not().Blank()).
	Do(func(val *Validation) {
		if mustBeAdmin {
			val.Is(String("staff", "role").EqualTo("admin"))
		}
	})

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "role": [
    "Role must be equal to \"admin\""
  ],
  "username": [
    "Username can't be blank"
  ]
}

func If added in v0.7.0

func If(condition bool, _validation *Validation) *Validation

The If(...) function is similar to [Merge](...), but merge the Validation session only when the condition is true, and returns the same Validation instance. When the condition is false, no operation is performed and the original instance is returned unchanged.

See [Merge](...) for more information.

Example
mustBeAdmin := true
val := Is(String("", "username").Not().Blank()).
	If(mustBeAdmin, Is(String("staff", "role").EqualTo("admin")))

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "role": [
    "Role must be equal to \"admin\""
  ],
  "username": [
    "Username can't be blank"
  ]
}

func In

func In(name string, v *Validation) *Validation

The In(...) function executes one or more validators in a namespace, so the value names in the error result are prefixed with this namespace. This is useful for validating nested structures.

In the following example we are validating the Person and the nested Address structure. We can distinguish the errors of the nested Address structure in the error results.

Example
type Address struct {
	Name   string
	Street string
}

type Person struct {
	Name    string
	Address Address
}

p := Person{"Bob", Address{"", "1600 Amphitheatre Pkwy"}}

val := Is(String(p.Name, "name").OfLengthBetween(4, 20)).
	In("address", Is(
		String(p.Address.Name, "name").Not().Blank()).Is(
		String(p.Address.Street, "street").Not().Blank()))

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "address.name": [
    "Name can't be blank"
  ],
  "name": [
    "Name must have a length between \"4\" and \"20\""
  ]
}

func InCell added in v0.7.0

func InCell(name string, index int, v *Validation) *Validation

The InCell(...) function executes one or more validators in an indexed namespace where the target is a scalar value (e.g., entries of a primitive slice). The value names in the error result are prefixed with this indexed namespace.

Example
// Example: Validating a slice of primitive values (strings)
tags := []string{"", "important", "urgent", ""}

val := Is(String("Project", "name").Not().Blank())

// Validate each tag in the slice using InCell
for i, tag := range tags {
	val.InCell("tags", i, Is(String(tag, "tag").Not().Blank()))
}

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "tags[0]": [
    "Tag can't be blank"
  ],
  "tags[3]": [
    "Tag can't be blank"
  ]
}

func InRow

func InRow(name string, index int, v *Validation) *Validation

The InRow(...) function executes one or more validators in a namespace similar to the In(...) function, but with indexed namespace. So, the value names in the error result are prefixed with this indexed namespace. It is useful for validating nested lists in structures.

In the following example we validate the Person and the nested list Addresses. The error results can distinguish the errors of the nested list Addresses.

Example
type Address struct {
	Name   string
	Street string
}

type Person struct {
	Name      string
	Addresses []Address
}

p := Person{
	"Bob",
	[]Address{
		{"", "1600 Amphitheatre Pkwy"},
		{"Home", ""},
	},
}

val := Is(String(p.Name, "name").OfLengthBetween(4, 20))

for i, a := range p.Addresses {
	val.InRow("addresses", i, Is(
		String(a.Name, "name").Not().Blank()).Is(
		String(a.Street, "street").Not().Blank()))
}

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "addresses[0].name": [
    "Name can't be blank"
  ],
  "addresses[1].street": [
    "Street can't be blank"
  ],
  "name": [
    "Name must have a length between \"4\" and \"20\""
  ]
}

func Is

func Is(validators ...Validator) *Validation

The Is(...) function allows you to pass a Validator with the value and the rules for validating it. At the same time, create a Validation session, which lets you add more Validators in order to verify more values.

As shown in the following example, we are passing to the function Is(...) the Validator for the full_name value. The function returns a Validation session that allows us to add more Validators to validate more values; in the example case the values age and status:

Example
val := Is(String("Bob", "full_name").Not().Blank().OfLengthBetween(4, 20)).
	Is(Number(17, "age").GreaterThan(18)).
	Is(String("singl", "status").InSlice([]string{"married", "single"}))

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "age": [
    "Age must be greater than \"18\""
  ],
  "full_name": [
    "Full name must have a length between \"4\" and \"20\""
  ],
  "status": [
    "Status is not valid"
  ]
}

func New

func New(options ...Options) *Validation

This function allows you to create a new Validation session without a Validator. This is useful for conditional validation, reusing validation logic or just to pass optional parameters to the Validation session.

The function accepts an optional parameter of type Options struct, which allows you to specify options such as the specific locale code and locale to use, and a custom JSON marshaler for errors.

The following example conditionally adds a validator rule for the month_day value.

Example
month := 5
monthDay := 11

val := New()

if month == 6 {
	val.Is(Number(monthDay, "month_day").LessOrEqualTo(10))
}

if val.Valid() {
	fmt.Println("The validation passes")
}
Output:
The validation passes

func When added in v0.7.0

func When(condition bool, function func(val *Validation)) *Validation

When(...) executes the given function passing the Validation instance only if the condition is true. When the condition is false, no operation is performed.

See Validation.When(...) for more information.

Example
mustBeAdmin := true
val := Is(String("", "username").Not().Blank()).
	When(mustBeAdmin, func(val *Validation) {
		val.Is(String("staff", "role").EqualTo("admin"))
	})

if !val.Valid() {
	// NOTE: sortedErrorMarshalForDocs is an optional parameter used here for
	// documentation purposes to ensure the order of keys in the JSON output.
	out, _ := json.MarshalIndent(val.Error(sortedErrorMarshalForDocs), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "role": [
    "Role must be equal to \"admin\""
  ],
  "username": [
    "Username can't be blank"
  ]
}

func (*Validation) AddErrorMessage

func (v *Validation) AddErrorMessage(name string, message string) *Validation

Add an error message to the Validation session without executing a field validator. By adding this error message, the Validation session will be marked as invalid.

func (*Validation) Check

func (validation *Validation) Check(validators ...Validator) *Validation

Check(...) adds one or more validators to a Validation session. But unlike [Is()], the validators are not short-circuited.

func (*Validation) Do added in v0.7.0

func (validation *Validation) Do(function func(val *Validation)) *Validation

The Do(...) function executes the given function with the current Validation instance and returns the same instance.

This allows you to extend a validation chain with additional or conditional rules in a concise way:

v.Is(v.String(username, "username").Not().Blank()).Do(func(val *v.Validation) {
	if isAdmin {
		val.Is(v.String(role, "role").Equal("admin"))
	}
})

func (*Validation) Error

func (validation *Validation) Error(marshalJsonFun ...func(e *Error) ([]byte, error)) error

Error returns the validation errors as a standard Go error interface.

DEPRECATED: This method is deprecated in favor of ToError() or ToValgoError(). The Error() method name conflicts with Go's error interface implementation convention, where Error() typically implements the error interface for a type.

Use ToError() for standard error handling or ToValgoError() for detailed validation error information.

func (*Validation) Errors

func (session *Validation) Errors() map[string]*valueError

Return a map with the information for each invalid field validator in the Validation session.

func (*Validation) If added in v0.7.0

func (validation *Validation) If(condition bool, _validation *Validation) *Validation

If(...) is similar to [Merge](...), but merge the Validation session only when the condition is true, and returns the same Validation instance. When the condition is false, no operation is performed and the original instance is returned unchanged.

See [Merge](...) for more information.

v.If(isAdmin, v.Is(v.String(username, "username").Not().Blank()) )

func (*Validation) In

func (validation *Validation) In(name string, _validation *Validation) *Validation

Add a map namespace to a Validation session.

func (*Validation) InCell added in v0.7.0

func (validation *Validation) InCell(name string, index int, _validation *Validation) *Validation

Add an indexed namespace to a Validation session where the target is a single, scalar value (e.g., entries of a primitive slice). This is useful for validating arrays or slices of primitives. Example:

validation := valgo.InCell("tag_priority", 0,
	valgo.Is(valgo.String("", "tag_priority", "Tag priority").Not().Blank()),
)

The example above validates the value at tag_priority[0].

func (*Validation) InRow

func (validation *Validation) InRow(name string, index int, _validation *Validation) *Validation

Add an indexed namespace to a Validation session.

func (*Validation) Is

func (validation *Validation) Is(validators ...Validator) *Validation

Add one or more validators to a Validation session.

func (*Validation) IsValid

func (validation *Validation) IsValid(name string) bool

Return true if a specific field validator is valid.

Example
val := Is(Number(16, "age").GreaterThan(18)).
	Is(String("single", "status").InSlice([]string{"married", "single"}))

if !val.IsValid("age") {
	fmt.Println("Warning: someone underage is trying to sign up")
}
Output:
Warning: someone underage is trying to sign up

func (*Validation) Merge

func (validation *Validation) Merge(_validation *Validation) *Validation

Using [Merge](...) you can merge two Validation sessions. When two validations are merged, errors with the same value name will be merged. It is useful for reusing validation logic.

The following example merges the Validation session returned by the validatePreStatus function. Since both Validation sessions validate a value with the name status, the error returned will return two error messages, and without duplicate the Not().Blank() error message rule.

Example
type Record struct {
	Name   string
	Status string
}

validatePreStatus := func(status string) *Validation {
	regex, _ := regexp.Compile("pre-.+")

	return Check(String(status, "status").Not().Blank().MatchingTo(regex))
}

r := Record{"Classified", ""}

val := Is(
	String(r.Name, "name").Not().Blank()).Is(
	String(r.Status, "status").Not().Blank())

val.Merge(validatePreStatus(r.Status))

if !val.Valid() {
	out, _ := json.MarshalIndent(val.Error(), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "status": [
    "Status can't be blank",
    "Status must match to \"pre-.+\""
  ]
}

func (*Validation) MergeError added in v0.3.0

func (v *Validation) MergeError(err *Error) *Validation

MergeError allows merging Valgo errors from an already validated Validation session. The function takes an Valgo Error pointer as an argument and returns a Validation pointer.

func (*Validation) MergeErrorIn added in v0.3.0

func (v *Validation) MergeErrorIn(name string, err *Error) *Validation

MergeErrorIn allows merging Valgo errors from already validated Validation sessions within a map namespace. The function takes a namespace name and an Error pointer as arguments and returns a Validation pointer.

func (*Validation) MergeErrorInIndex added in v0.7.0

func (v *Validation) MergeErrorInIndex(name string, index int, err *Error) *Validation

MergeErrorInRow allows merging Valgo errors from already validated Validation sessions within an indexed namespace. These are errors added by InRow() and InCell() validations. The function takes a namespace name, an index, and an Error pointer as arguments and returns a Validation pointer.

func (*Validation) MergeErrorInRow added in v0.3.0

func (v *Validation) MergeErrorInRow(name string, index int, err *Error) *Validation

MergeErrorInRow allows merging Valgo errors from already validated Validation sessions within an indexed namespace. The function takes a namespace name, an index, and an Error pointer as arguments and returns a Validation pointer.

DEPRECATED: This method is deprecated in favor of MergeErrorInIndex(). The MergeErrorInIndex() method is a generic name to cover errors added by InRow() and InCell() validations.

func (*Validation) ToError added in v0.5.0

func (validation *Validation) ToError(marshalJsonFun ...func(e *Error) ([]byte, error)) error

ToError returns the validation errors as a standard Go error interface.

This method is useful for idiomatic error handling and integration with Go's native error system. It returns the same underlying error value as ToValgoError() but typed as the error interface.

Example:

val := Is(String("", "name").Not().Blank())
if err := val.ToError(); err != nil {
    log.Printf("Validation failed: %v", err)
    return err
}

An optional JSON marshaling function can be passed to customize how the validation errors are serialized into JSON. If no function is provided, a default marshaling behavior is used.

func (*Validation) ToValgoError added in v0.5.0

func (validation *Validation) ToValgoError(marshalJsonFun ...func(e *Error) ([]byte, error)) *Error

ToValgoError returns the validation errors as a *valgo.Error type, providing access to rich, structured error details. It's essentially a shortcut to `ToError().(*valgo.Error)`.

This method returns the underlying *valgo.Error type directly, exposing detailed validation information such as per-field messages, templates, and localized titles. It's the single source of truth for validation errors.

Example:

val := Is(String("", "name").Not().Blank())
if errInfo := val.ToValgoError(); errInfo != nil {
    for field, valueError := range errInfo.Errors() {
        fmt.Printf("Field '%s': %v\n", field, valueError.Messages())
    }
}

An optional JSON marshaling function can be passed to customize how the validation errors are serialized into JSON. If no function is provided, a default marshaling behavior is used.

func (*Validation) Valid

func (validation *Validation) Valid() bool

A Validation session provides this function which returns either true if all their validators are valid or false if any one of them is invalid.

In the following example, even though the Validator for age is valid, the Validator for status is invalid, making the entire Validator session invalid.

Example
val := Is(Number(21, "age").GreaterThan(18)).
	Is(String("singl", "status").InSlice([]string{"married", "single"}))

if !val.Valid() {
	out, _ := json.MarshalIndent(val.Error(), "", "  ")
	fmt.Println(string(out))
}
Output:
{
  "status": [
    "Status is not valid"
  ]
}

func (*Validation) When added in v0.7.0

func (validation *Validation) When(condition bool, function func(val *Validation)) *Validation

When(...) is similar to Do(...), but executes the given function only when the condition is true, and returns the same Validation instance. When the condition is false, no operation is performed and the original instance is returned unchanged.

See Do(...) for the unconditional variant.

v.Is(v.String(username, "username").Not().Blank()).When(isAdmin, func(val *v.Validation) {
	val.Is(v.String(role, "role").Equal("admin"))
})

type ValidationFactory added in v0.2.4

type ValidationFactory struct {
	// contains filtered or unexported fields
}

func Factory added in v0.2.0

func Factory(options FactoryOptions) *ValidationFactory

Factory is a function used to create a Valgo factory.

With a Valgo factory, you can create Validation sessions with preset options, avoiding having to pass options each time when a Validation session is created.

This allows for more flexibility and easier management of options.

The Factory function accepts an options parameter of type FactoryOptions struct, which allows you to specify options such as the default locale code, available locales and a custom JSON marshaler for errors.

func (*ValidationFactory) AddErrorMessage added in v0.2.4

func (_factory *ValidationFactory) AddErrorMessage(name string, message string) *Validation

Create a new Validation session, through a factory, and add an error message to it without executing a field validator. By adding this error message, the Validation session will be marked as invalid.

func (*ValidationFactory) Check added in v0.2.4

func (_factory *ValidationFactory) Check(v Validator) *Validation

The Check function, through a factory, is similar to the Is function, however with Check the Rules of the Validator parameter are not short-circuited, which means that regardless of whether a previous rule was valid, all rules are checked.

The function is similar to the [Check()] function, but it uses a factory. For more information see the [Check()] function.

func (*ValidationFactory) Do added in v0.7.0

func (_factory *ValidationFactory) Do(function func(val *Validation)) *Validation

The Do function executes the given function with the current Validation instance and returns the same instance.

See Validation.Do(...) for more information.

func (*ValidationFactory) If added in v0.7.0

func (_factory *ValidationFactory) If(condition bool, _validation *Validation) *Validation

If(...) is similar to [Merge](...), but merge the Validation session only when the condition is true, and returns the same Validation instance. When the condition is false, no operation is performed and the original instance is returned unchanged.

See [Merge](...) for more information.

func (*ValidationFactory) In added in v0.2.4

func (_factory *ValidationFactory) In(name string, v *Validation) *Validation

The In function executes, through a factory, one or more validators in a namespace, so the value names in the error result are prefixed with this namespace. This is useful for validating nested structures.

The function is similar to the [In()] function, but it uses a factory. For more information see the [In()] function.

func (*ValidationFactory) InCell added in v0.7.0

func (_factory *ValidationFactory) InCell(name string, index int, v *Validation) *Validation

The InCell function executes, through a factory, one or more validators in an indexed namespace where the target is a scalar value (e.g., entries of a primitive slice). The value names in the error result are prefixed with this indexed namespace.

The function is similar to the [InCell()] function, but it uses a factory. For more information see the [InCell()] function.

func (*ValidationFactory) InRow added in v0.2.4

func (_factory *ValidationFactory) InRow(name string, index int, v *Validation) *Validation

The InRow function executes, through a factory, one or more validators in a namespace similar to the In(...) function, but with indexed namespace. So,\ the value names in the error result are prefixed with this indexed namespace. It is useful for validating nested lists in structures.

The function is similar to the [InRow()] function, but it uses a factory. For more information see the [InRow()] function.

func (*ValidationFactory) Is added in v0.2.4

func (_factory *ValidationFactory) Is(v Validator) *Validation

The Is function allows you to pass, through a factory, a Validator with the value and the rules for validating it. At the same time, create a Validation session, which lets you add more Validators in order to verify more values.

The function is similar to the [Is()] function, but it uses a factory. For more information see the [Is()] function.

func (*ValidationFactory) New added in v0.2.4

func (_factory *ValidationFactory) New(options ...Options) *Validation

This New function allows you to create, through a factory, a new Validation session without a Validator. This is useful for conditional validation or reusing validation logic.

The function is similar to the [New()] function, but it uses a factory. For more information see the [New()] function.

func (*ValidationFactory) When added in v0.7.0

func (_factory *ValidationFactory) When(condition bool, function func(val *Validation)) *Validation

The When function executes the given function passing the Validation instance only if the condition is true. When the condition is false, no operation is performed.

See Validation.When(...) for more information.

type Validator

type Validator interface {
	Context() *ValidatorContext
}

Interface implemented by valgo Validators and custom Validators.

type ValidatorAny

type ValidatorAny struct {
	// contains filtered or unexported fields
}

The Any validator's type that keeps its validator context.

func Any

func Any(value any, nameAndTitle ...string) *ValidatorAny

Receive a value to validate.

The value can be any type;

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A value_%N` pattern is used as a name in the error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name phone_number will be humanized as Phone Number.

func (*ValidatorAny) Context

func (validator *ValidatorAny) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorAny) EqualTo

func (validator *ValidatorAny) EqualTo(value any, template ...string) *ValidatorAny

Validate if a value is equal to another. This function internally uses the golang `==` operator. For example:

status := "running"
Is(v.Any(status).Equal("running"))

DEPRECATED: 'any' is not safely comparable. Use the Comparable validator instead. This function will be removed in Valgo v1.0.0.

func (*ValidatorAny) Nil

func (validator *ValidatorAny) Nil(template ...string) *ValidatorAny

Validate if a value is nil. For example:

var status *string
Is(v.Any(status).Nil())

func (*ValidatorAny) Not

func (validator *ValidatorAny) Not() *ValidatorAny

Invert the logical value associated with the next validator function. For example:

// It will return false because `Not()` inverts the boolean value associated with the `Equal()` function
Is(v.Any("a").Not().Equal("a")).Valid()

func (*ValidatorAny) Or added in v0.3.0

func (validator *ValidatorAny) Or() *ValidatorAny

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the string is equals "test".
input := "test"
isValid := v.Is(v.String(input).MinLength(5).Or().EqualTo("test")).Valid()

func (*ValidatorAny) Passing

func (validator *ValidatorAny) Passing(function func(v any) bool, template ...string) *ValidatorAny

Validate if a value passes a custom function. For example:

status := ""
Is(v.Any(status).Passing((v any) bool {
	return v == getNewStatus()
})

type ValidatorBool

type ValidatorBool[T ~bool] struct {
	// contains filtered or unexported fields
}

The Boolean validator type that keeps its validator context.

func Bool

func Bool[T ~bool](value T, nameAndTitle ...string) *ValidatorBool[T]

func (*ValidatorBool[T]) Context

func (validator *ValidatorBool[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorBool[T]) EqualTo

func (validator *ValidatorBool[T]) EqualTo(value T, template ...string) *ValidatorBool[T]

Validate if a boolean value is equal to another. For example:

activated := true
Is(v.Bool(activated).Equal(true))

func (*ValidatorBool[T]) False

func (validator *ValidatorBool[T]) False(template ...string) *ValidatorBool[T]

Validate if a boolean value is false. For example:

activated := false
Is(v.Bool(activated).Equal(true)).Valid()

func (*ValidatorBool[T]) InSlice

func (validator *ValidatorBool[T]) InSlice(slice []T, template ...string) *ValidatorBool[T]

Validate if the value of a boolean pointer is present in a boolean slice. For example:

activated := false
elements := []bool{true, false, true}
Is(v.Bool(activated).InSlice(elements))

func (*ValidatorBool[T]) Not

func (validator *ValidatorBool[T]) Not() *ValidatorBool[T]

Invert the boolean value associated with the next validator function. For example:

// It will return false because `Not()` inverts the boolean value associated with the True() function
Is(v.Bool(true).Not().True()).Valid()

func (*ValidatorBool[T]) Or added in v0.3.0

func (validator *ValidatorBool[T]) Or() *ValidatorBool[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is equals false.
input := true
isValid := v.Is(v.Bool(input).False().Or().True()).Valid()

func (*ValidatorBool[T]) Passing

func (validator *ValidatorBool[T]) Passing(function func(v T) bool, template ...string) *ValidatorBool[T]

Validate if a boolean value pass a custom function. For example:

activated := false
Is(v.Bool(activated).Passing((v bool) bool {
	return v == someBoolFunction()
})

func (*ValidatorBool[T]) True

func (validator *ValidatorBool[T]) True(template ...string) *ValidatorBool[T]

Validate if a boolean value is true. For example:

activated := true
Is(v.Bool(activated).True())

type ValidatorBoolP

type ValidatorBoolP[T ~bool] struct {
	// contains filtered or unexported fields
}

The Boolean pointer validator type that keeps its validator context.

func BoolP

func BoolP[T ~bool](value *T, nameAndTitle ...string) *ValidatorBoolP[T]

Receives a boolean pointer to validate.

The value also can be a custom boolean type such as `type Active bool;`

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorBoolP[T]) Context

func (validator *ValidatorBoolP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorBoolP[T]) EqualTo

func (validator *ValidatorBoolP[T]) EqualTo(value T, template ...string) *ValidatorBoolP[T]

Validate if the value of a boolean pointer is equal to another value. For example:

activated := true
Is(v.BoolP(&activated).Equal(true))

func (*ValidatorBoolP[T]) False

func (validator *ValidatorBoolP[T]) False(template ...string) *ValidatorBoolP[T]

Validate if the value of a boolean pointer is false. For example:

activated := false
Is(v.BoolP(&activated).False())

func (*ValidatorBoolP[T]) FalseOrNil

func (validator *ValidatorBoolP[T]) FalseOrNil(template ...string) *ValidatorBoolP[T]

Validate if the value of a boolean pointer is false or nil. For example:

var activated *bool
Is(v.BoolP(activated).FalseOrNil())
*activated = false
Is(v.BoolP(activated).FalseOrNil())

func (*ValidatorBoolP[T]) InSlice

func (validator *ValidatorBoolP[T]) InSlice(slice []T, template ...string) *ValidatorBoolP[T]

Validate if the value of a boolean pointer is present in a boolean slice. For example:

activated := false
elements := []bool{true, false, true}
Is(v.BoolP(&activated).InSlice(elements))

func (*ValidatorBoolP[T]) Nil

func (validator *ValidatorBoolP[T]) Nil(template ...string) *ValidatorBoolP[T]

Validate if a boolean pointer is nil. For example:

var activated *bool
Is(v.BoolP(activated).Nil())

func (*ValidatorBoolP[T]) Not

func (validator *ValidatorBoolP[T]) Not() *ValidatorBoolP[T]

Invert the boolean value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the True() function
activated := true
Is(v.BoolP(&activated).Not().True()).Valid()

func (*ValidatorBoolP[T]) Or added in v0.3.0

func (validator *ValidatorBoolP[T]) Or() *ValidatorBoolP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is equals false.
input := true
isValid := v.Is(v.BoolP(&input).Nil().Or().EqualTo(false)).Valid()

func (*ValidatorBoolP[T]) Passing

func (validator *ValidatorBoolP[T]) Passing(function func(v *T) bool, template ...string) *ValidatorBoolP[T]

Validate if a boolean pointer pass a custom function. For example:

activated := false
Is(v.BoolP(&activated).Passing((v *bool) bool {
	return *v == someBoolFunction()
})

func (*ValidatorBoolP[T]) True

func (validator *ValidatorBoolP[T]) True(template ...string) *ValidatorBoolP[T]

Validate if the value of a boolean pointer is true. For example:

activated := true
Is(v.BoolP(&activated).True())

type ValidatorComparable added in v0.7.0

type ValidatorComparable[T comparable] struct {
	// contains filtered or unexported fields
}

The Comparable validator's type that keeps its validator context. T can be any Go type (pointer, struct, etc.) that is comparable.

func Comparable added in v0.7.0

func Comparable[T comparable](value T, nameAndTitle ...string) *ValidatorComparable[T]

Receive a value of type T to validate, where T must be comparable.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A value_%N pattern is used as a name in the error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name phone_number will be humanized as Phone Number.

Example:

v.Is(v.Comparable(user).Not().Nil())

func (*ValidatorComparable[T]) Context added in v0.7.0

func (validator *ValidatorComparable[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorComparable[T]) EqualTo added in v0.7.0

func (validator *ValidatorComparable[T]) EqualTo(value T, template ...string) *ValidatorComparable[T]

Validate if a value is equal to another. This function internally uses the golang `==` operator. For example:

status := "running"
Is(v.Comparable(status).EqualTo("running"))

func (*ValidatorComparable[T]) InSlice added in v0.7.0

func (validator *ValidatorComparable[T]) InSlice(slice []T, template ...string) *ValidatorComparable[T]

Validate if a value is present in a slice. For example:

status := "idle"
validStatus := []string{"idle", "paused", "stopped"}
Is(v.Comparable(status).InSlice(validStatus))

func (*ValidatorComparable[T]) Not added in v0.7.0

func (validator *ValidatorComparable[T]) Not() *ValidatorComparable[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because `Not()` inverts the boolean value associated with `EqualTo()`
v.Is(v.Comparable("a").Not().EqualTo("a")).Valid()

func (*ValidatorComparable[T]) Or added in v0.7.0

func (validator *ValidatorComparable[T]) Or() *ValidatorComparable[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the string is equals "running".
status := "running"
isValid := v.Is(v.Comparable(status).EqualTo("paused").Or().EqualTo("running")).Valid()

func (*ValidatorComparable[T]) Passing added in v0.7.0

func (validator *ValidatorComparable[T]) Passing(function func(v T) bool, template ...string) *ValidatorComparable[T]

Validate if a value passes a custom function. The function receives a typed T value, enabling compile-time type safety.

For example:

type Status string
status := Status("running")
isValid := v.Is(
  v.Comparable(status).Passing(func(s Status) bool {
    return s == "running" || s == "paused"
  }),
).Valid()

type ValidatorComparableP added in v0.7.0

type ValidatorComparableP[T comparable] struct {
	// contains filtered or unexported fields
}

The Comparable validator's type that keeps its validator context. T can be any Go type (pointer, struct, etc.) that is comparable.

func ComparableP added in v0.7.0

func ComparableP[T comparable](value *T, nameAndTitle ...string) *ValidatorComparableP[T]

Receive a value of type T to validate, where T must be comparable.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A value_%N pattern is used as a name in the error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name phone_number will be humanized as Phone Number.

Example:

v.Is(v.Comparable(user).Not().Nil())

func (*ValidatorComparableP[T]) Context added in v0.7.0

func (validator *ValidatorComparableP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorComparableP[T]) EqualTo added in v0.7.0

func (validator *ValidatorComparableP[T]) EqualTo(value T, template ...string) *ValidatorComparableP[T]

Validate if a value is equal to another. This function internally uses the golang `==` operator. For example:

status := "running"
Is(v.Comparable(status).EqualTo("running"))

func (*ValidatorComparableP[T]) InSlice added in v0.7.0

func (validator *ValidatorComparableP[T]) InSlice(slice []T, template ...string) *ValidatorComparableP[T]

Validate if a value is present in a slice. For example:

status := "idle"
validStatus := []string{"idle", "paused", "stopped"}
Is(v.Comparable(status).InSlice(validStatus))

func (*ValidatorComparableP[T]) Nil added in v0.7.0

func (validator *ValidatorComparableP[T]) Nil(template ...string) *ValidatorComparableP[T]

Validate if a value is nil. Works for nil-able kinds: pointers, slices, maps, chans, funcs, and interfaces. For non-nil-able types, this will return false.

For example:

var s *string
v.Is(v.Comparable(s).Nil())

func (*ValidatorComparableP[T]) Not added in v0.7.0

func (validator *ValidatorComparableP[T]) Not() *ValidatorComparableP[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because `Not()` inverts the boolean value associated with `EqualTo()`
v.Is(v.Comparable("a").Not().EqualTo("a")).Valid()

func (*ValidatorComparableP[T]) Or added in v0.7.0

func (validator *ValidatorComparableP[T]) Or() *ValidatorComparableP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the string is equals "running".
status := "running"
isValid := v.Is(v.Comparable(status).EqualTo("paused").Or().EqualTo("running")).Valid()

func (*ValidatorComparableP[T]) Passing added in v0.7.0

func (validator *ValidatorComparableP[T]) Passing(function func(v *T) bool, template ...string) *ValidatorComparableP[T]

Validate if a value passes a custom function. The function receives a typed T value, enabling compile-time type safety.

For example:

type Status string
status := Status("running")
isValid := v.Is(
  v.Comparable(status).Passing(func(s Status) bool {
    return s == "running" || s == "paused"
  }),
).Valid()

type ValidatorContext

type ValidatorContext struct {
	// contains filtered or unexported fields
}

The context keeps the state and provides the functions to control a custom validator.

func NewContext

func NewContext(value any, nameAndTitle ...string) *ValidatorContext

Create a new ValidatorContext to be used by a custom validator.

func (*ValidatorContext) Add

func (ctx *ValidatorContext) Add(function func() bool, errorKey string, template ...string) *ValidatorContext

Add a function to a custom validator.

func (*ValidatorContext) AddWithParams

func (ctx *ValidatorContext) AddWithParams(function func() bool, errorKey string, templateParams map[string]any, template ...string) *ValidatorContext

Add a function to a custom validator and pass a map with values used for the validator function to be displayed in the error message.

func (*ValidatorContext) AddWithValue

func (ctx *ValidatorContext) AddWithValue(function func() bool, errorKey string, value any, template ...string) *ValidatorContext

Add a function to a custom validator and pass a value used for the validator function to be displayed in the error message.

Use [AddWithParams()] if the error message requires more input values.

func (*ValidatorContext) Not

func (ctx *ValidatorContext) Not() *ValidatorContext

Invert the boolean value associated with the next validator function in a custom validator.

func (*ValidatorContext) Or added in v0.3.0

Add Or operation to validation.

func (*ValidatorContext) Value

func (ctx *ValidatorContext) Value() any

Return the value being validated in a custom validator.

type ValidatorFloat added in v0.7.0

type ValidatorFloat[T ~float32 | ~float64] struct {
	// contains filtered or unexported fields
}

The ValidatorFloat provides functions for setting validation rules for a float value types, or a custom type based on a float32 or float64.

func Float32

func Float32[T ~float32](value T, nameAndTitle ...string) *ValidatorFloat[T]

Receives a float32 value to validate.

The value can also be a custom float32 type such as type Price float32.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Float64

func Float64[T ~float64](value T, nameAndTitle ...string) *ValidatorFloat[T]

Receives a float64 value to validate.

The value can also be a custom float64 type such as type Price float64.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorFloat[T]) Between added in v0.7.0

func (validator *ValidatorFloat[T]) Between(min T, max T, template ...string) *ValidatorFloat[T]

Validate if a number is within a range (inclusive). For example:

Is(v.Float32(3).Between(2,6))

func (*ValidatorFloat[T]) Context added in v0.7.0

func (validator *ValidatorFloat[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorFloat[T]) EqualTo added in v0.7.0

func (validator *ValidatorFloat[T]) EqualTo(value T, template ...string) *ValidatorFloat[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := float32(2)
Is(v.Float32(quantity).EqualTo(2))

func (*ValidatorFloat[T]) Finite added in v0.7.0

func (validator *ValidatorFloat[T]) Finite(template ...string) *ValidatorFloat[T]

Validate if a numeric value is finite (not NaN and not infinite).

For example:

Is(v.Float32(3.14).Finite())

func (*ValidatorFloat[T]) GreaterOrEqualTo added in v0.7.0

func (validator *ValidatorFloat[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorFloat[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := float32(3)
Is(v.Float32(quantity).GreaterOrEqualTo(3))

func (*ValidatorFloat[T]) GreaterThan added in v0.7.0

func (validator *ValidatorFloat[T]) GreaterThan(value T, template ...string) *ValidatorFloat[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := float32(3)
Is(v.Float32(quantity).GreaterThan(2))

func (*ValidatorFloat[T]) InSlice added in v0.7.0

func (validator *ValidatorFloat[T]) InSlice(slice []T, template ...string) *ValidatorFloat[T]

Validate if a number is present in a numeric slice. For example:

quantity := float32(3)
validQuantities := []float32{1,3,5}
Is(v.Float32(quantity).InSlice(validQuantities))

func (*ValidatorFloat[T]) Infinite added in v0.7.0

func (validator *ValidatorFloat[T]) Infinite(template ...string) *ValidatorFloat[T]

Validate if a numeric value is infinite (positive or negative infinity).

For example:

Is(v.Float32(math.Inf(1)).Infinite())

func (*ValidatorFloat[T]) LessOrEqualTo added in v0.7.0

func (validator *ValidatorFloat[T]) LessOrEqualTo(value T, template ...string) *ValidatorFloat[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := float32(2)
Is(v.Float32(quantity).LessOrEqualTo(2))

func (*ValidatorFloat[T]) LessThan added in v0.7.0

func (validator *ValidatorFloat[T]) LessThan(value T, template ...string) *ValidatorFloat[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := float32(2)
Is(v.Float32(quantity).LessThan(3))

func (*ValidatorFloat[T]) NaN added in v0.7.0

func (validator *ValidatorFloat[T]) NaN(template ...string) *ValidatorFloat[T]

Validate if a numeric value is NaN (Not a Number).

For example:

Is(v.Float32(math.NaN()).NaN())

func (*ValidatorFloat[T]) Negative added in v0.7.0

func (validator *ValidatorFloat[T]) Negative(template ...string) *ValidatorFloat[T]

Validate if a numeric value is negative (less than zero).

For example:

Is(v.Float32(-5.5).Negative())

func (*ValidatorFloat[T]) Not added in v0.7.0

func (validator *ValidatorFloat[T]) Not() *ValidatorFloat[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
Is(v.Float32(0).Not().Zero()).Valid()

func (*ValidatorFloat[T]) Or added in v0.7.0

func (validator *ValidatorFloat[T]) Or() *ValidatorFloat[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := float32(0)
isValid := v.Is(v.Float32(input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorFloat[T]) Passing added in v0.7.0

func (validator *ValidatorFloat[T]) Passing(function func(v T) bool, template ...string) *ValidatorFloat[T]

Validate if a numeric value passes a custom function. For example:

quantity := float32(2)
Is(v.Float32(quantity).Passing((v float32) bool {
	return v == getAllowedQuantity()
})

func (*ValidatorFloat[T]) Positive added in v0.7.0

func (validator *ValidatorFloat[T]) Positive(template ...string) *ValidatorFloat[T]

Validate if a numeric value is positive (greater than zero).

For example:

Is(v.Float32(5.5).Positive())

func (*ValidatorFloat[T]) Zero added in v0.7.0

func (validator *ValidatorFloat[T]) Zero(template ...string) *ValidatorFloat[T]

Validate if a numeric value is zero.

For example:

Is(v.Float32(0).Zero())

type ValidatorFloatP added in v0.7.0

type ValidatorFloatP[T ~float32 | ~float64] struct {
	// contains filtered or unexported fields
}

The ValidatorFloatP provides functions for setting validation rules for a float pointer value types, or a custom type based on a float32 or float64 pointer.

func Float32P

func Float32P[T ~float32](value *T, nameAndTitle ...string) *ValidatorFloatP[T]

Receives a float32 pointer value to validate.

The value can also be a custom float32 pointer type such as type Price *float32.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Float64P

func Float64P[T ~float64](value *T, nameAndTitle ...string) *ValidatorFloatP[T]

Receives a float64 pointer value to validate.

The value can also be a custom float64 pointer type such as type Price *float64.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorFloatP[T]) Between added in v0.7.0

func (validator *ValidatorFloatP[T]) Between(min T, max T, template ...string) *ValidatorFloatP[T]

Validate if a number is within a range (inclusive). For example:

n := float32(3)
Is(v.Float32P(&n).Between(2,6))

func (*ValidatorFloatP[T]) Context added in v0.7.0

func (validator *ValidatorFloatP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorFloatP[T]) EqualTo added in v0.7.0

func (validator *ValidatorFloatP[T]) EqualTo(value T, template ...string) *ValidatorFloatP[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := float32(2)
Is(v.Float32P(&quantity).EqualTo(2))

func (*ValidatorFloatP[T]) Finite added in v0.7.0

func (validator *ValidatorFloatP[T]) Finite(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is finite (not NaN and not infinite).

For example:

n := float32(3.14)
Is(v.Float32P(&n).Finite())

func (*ValidatorFloatP[T]) GreaterOrEqualTo added in v0.7.0

func (validator *ValidatorFloatP[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorFloatP[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := float32(3)
Is(v.Float32P(&quantity).GreaterOrEqualTo(3))

func (*ValidatorFloatP[T]) GreaterThan added in v0.7.0

func (validator *ValidatorFloatP[T]) GreaterThan(value T, template ...string) *ValidatorFloatP[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := float32(3)
Is(v.Float32P(&quantity).GreaterThan(2))

func (*ValidatorFloatP[T]) InSlice added in v0.7.0

func (validator *ValidatorFloatP[T]) InSlice(slice []T, template ...string) *ValidatorFloatP[T]

Validate if a number is present in a numeric slice. For example:

quantity := float32(3)
validQuantities := []float32{1,3,5}
Is(v.Float32P(&quantity).InSlice(validQuantities))

func (*ValidatorFloatP[T]) Infinite added in v0.7.0

func (validator *ValidatorFloatP[T]) Infinite(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is infinite (positive or negative infinity).

For example:

n := float32(math.Inf(1))
Is(v.Float32P(&n).Infinite())

func (*ValidatorFloatP[T]) LessOrEqualTo added in v0.7.0

func (validator *ValidatorFloatP[T]) LessOrEqualTo(value T, template ...string) *ValidatorFloatP[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := float32(2)
Is(v.Float32P(&quantity).LessOrEqualTo(2))

func (*ValidatorFloatP[T]) LessThan added in v0.7.0

func (validator *ValidatorFloatP[T]) LessThan(value T, template ...string) *ValidatorFloatP[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := float32(2)
Is(v.Float32P(&quantity).LessThan(3))

func (*ValidatorFloatP[T]) NaN added in v0.7.0

func (validator *ValidatorFloatP[T]) NaN(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is NaN (Not a Number).

For example:

n := float32(math.NaN())
Is(v.Float32P(&n).NaN())

func (*ValidatorFloatP[T]) Negative added in v0.7.0

func (validator *ValidatorFloatP[T]) Negative(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is negative (less than zero).

For example:

n := float32(-5.5)
Is(v.Float32P(&n).Negative())

func (*ValidatorFloatP[T]) Nil added in v0.7.0

func (validator *ValidatorFloatP[T]) Nil(template ...string) *ValidatorFloatP[T]

Validate if a numeric pointer value is nil.

For example:

var n *float32
Is(v.Float32P(n).Nil())

func (*ValidatorFloatP[T]) Not added in v0.7.0

func (validator *ValidatorFloatP[T]) Not() *ValidatorFloatP[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
n := float32(0)
Is(v.Float32P(&n).Not().Zero()).Valid()

func (*ValidatorFloatP[T]) Or added in v0.7.0

func (validator *ValidatorFloatP[T]) Or() *ValidatorFloatP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := float32(0)
isValid := v.Is(v.Float32P(&input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorFloatP[T]) Passing added in v0.7.0

func (validator *ValidatorFloatP[T]) Passing(function func(v *T) bool, template ...string) *ValidatorFloatP[T]

Validate if a numeric value passes a custom function. For example:

quantity := float32(2)
Is(v.Float32P(&quantity).Passing((v *float32) bool {
	return *v == getAllowedQuantity()
})

func (*ValidatorFloatP[T]) Positive added in v0.7.0

func (validator *ValidatorFloatP[T]) Positive(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is positive (greater than zero).

For example:

n := float32(5.5)
Is(v.Float32P(&n).Positive())

func (*ValidatorFloatP[T]) Zero added in v0.7.0

func (validator *ValidatorFloatP[T]) Zero(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is zero.

For example:

n := float32(0)
Is(v.Float32P(&n).Zero())

func (*ValidatorFloatP[T]) ZeroOrNil added in v0.7.0

func (validator *ValidatorFloatP[T]) ZeroOrNil(template ...string) *ValidatorFloatP[T]

Validate if a numeric value is zero or nil.

For example:

n := float32(0)
Is(v.Float32P(&n).ZeroOrNil())

var n *float32
Is(v.Float32P(n).ZeroOrNil())

type ValidatorInt

type ValidatorInt[T ~int | ~int8 | ~int16 | ~int32 | ~int64] struct {
	// contains filtered or unexported fields
}

The ValidatorInt provides functions for setting validation rules for a int value types, or a custom type based on a int, int8, int16, int32, or int64.

func Int

func Int[T ~int](value T, nameAndTitle ...string) *ValidatorInt[T]

Receives an int value to validate.

The value can also be a custom int type such as type Age int.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int8

func Int8[T ~int8](value T, nameAndTitle ...string) *ValidatorInt[T]

Receives an int8 value to validate.

The value can also be a custom int8 type such as type Age int8.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int16

func Int16[T ~int16](value T, nameAndTitle ...string) *ValidatorInt[T]

Receives an int16 value to validate.

The value can also be a custom int16 type such as type Age int16.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int32

func Int32[T ~int32](value T, nameAndTitle ...string) *ValidatorInt[T]

Receives an int32 value to validate.

The value can also be a custom int32 type such as type Age int32.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int64

func Int64[T ~int64](value T, nameAndTitle ...string) *ValidatorInt[T]

Receives an int64 value to validate.

The value can also be a custom int64 type such as type Age int64.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Rune

func Rune[T ~rune](value T, nameAndTitle ...string) *ValidatorInt[T]

Receives a rune value to validate.

The value can also be a custom rune type such as type Age rune.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorInt[T]) Between

func (validator *ValidatorInt[T]) Between(min T, max T, template ...string) *ValidatorInt[T]

Validate if a number is within a range (inclusive). For example:

Is(v.Int(3).Between(2,6))

func (*ValidatorInt[T]) Context

func (validator *ValidatorInt[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorInt[T]) EqualTo

func (validator *ValidatorInt[T]) EqualTo(value T, template ...string) *ValidatorInt[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := int(2)
Is(v.Int(quantity).EqualTo(2))

func (*ValidatorInt[T]) GreaterOrEqualTo

func (validator *ValidatorInt[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorInt[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := int(3)
Is(v.Int(quantity).GreaterOrEqualTo(3))

func (*ValidatorInt[T]) GreaterThan

func (validator *ValidatorInt[T]) GreaterThan(value T, template ...string) *ValidatorInt[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := int(3)
Is(v.Int(quantity).GreaterThan(2))

func (*ValidatorInt[T]) InSlice

func (validator *ValidatorInt[T]) InSlice(slice []T, template ...string) *ValidatorInt[T]

Validate if a number is present in a numeric slice. For example:

quantity := int(3)
validQuantities := []int{1,3,5}
Is(v.Int(quantity).InSlice(validQuantities))

func (*ValidatorInt[T]) LessOrEqualTo

func (validator *ValidatorInt[T]) LessOrEqualTo(value T, template ...string) *ValidatorInt[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := int(2)
Is(v.Int(quantity).LessOrEqualTo(2))

func (*ValidatorInt[T]) LessThan

func (validator *ValidatorInt[T]) LessThan(value T, template ...string) *ValidatorInt[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := int(2)
Is(v.Int(quantity).LessThan(3))

func (*ValidatorInt[T]) Negative added in v0.7.0

func (validator *ValidatorInt[T]) Negative(template ...string) *ValidatorInt[T]

Validate if a numeric value is negative (less than zero).

For example:

Is(v.Int(-5).Negative())

func (*ValidatorInt[T]) Not

func (validator *ValidatorInt[T]) Not() *ValidatorInt[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
Is(v.Int(0).Not().Zero()).Valid()

func (*ValidatorInt[T]) Or added in v0.3.0

func (validator *ValidatorInt[T]) Or() *ValidatorInt[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := int(0)
isValid := v.Is(v.Int(input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorInt[T]) Passing

func (validator *ValidatorInt[T]) Passing(function func(v T) bool, template ...string) *ValidatorInt[T]

Validate if a numeric value passes a custom function. For example:

quantity := int(2)
Is(v.Int(quantity).Passing((v int) bool {
	return v == getAllowedQuantity()
})

func (*ValidatorInt[T]) Positive added in v0.7.0

func (validator *ValidatorInt[T]) Positive(template ...string) *ValidatorInt[T]

Validate if a numeric value is positive (greater than zero).

For example:

Is(v.Int(5).Positive())

func (*ValidatorInt[T]) Zero

func (validator *ValidatorInt[T]) Zero(template ...string) *ValidatorInt[T]

Validate if a numeric value is zero.

For example:

Is(v.Int(0).Zero())

type ValidatorIntP

type ValidatorIntP[T ~int | ~int8 | ~int16 | ~int32 | ~int64] struct {
	// contains filtered or unexported fields
}

The ValidatorIntP provides functions for setting validation rules for a int pointer value types, or a custom type based on a int, int8, int16, int32, or int64 pointer.

func Int8P

func Int8P[T ~int8](value *T, nameAndTitle ...string) *ValidatorIntP[T]

Receives an int8 pointer value to validate.

The value can also be a custom int8 pointer type such as type Age *int8.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int16P

func Int16P[T ~int16](value *T, nameAndTitle ...string) *ValidatorIntP[T]

Receives an int16 pointer value to validate.

The value can also be a custom int16 pointer type such as type Age *int16.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int32P

func Int32P[T ~int32](value *T, nameAndTitle ...string) *ValidatorIntP[T]

Receives an int32 pointer value to validate.

The value can also be a custom int32 pointer type such as type Age *int32.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Int64P

func Int64P[T ~int64](value *T, nameAndTitle ...string) *ValidatorIntP[T]

Receives an int64 pointer value to validate.

The value can also be a custom int64 pointer type such as type Age *int64.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func IntP

func IntP[T ~int](value *T, nameAndTitle ...string) *ValidatorIntP[T]

Receives an int pointer value to validate.

The value can also be a custom int pointer type such as type Age *int.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func RuneP

func RuneP[T ~rune](value *T, nameAndTitle ...string) *ValidatorIntP[T]

Receives a rune pointer value to validate.

The value can also be a custom rune pointer type such as type Age *rune.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorIntP[T]) Between

func (validator *ValidatorIntP[T]) Between(min T, max T, template ...string) *ValidatorIntP[T]

Validate if a number is within a range (inclusive). For example:

n := int(3)
Is(v.IntP(&n).Between(2,6))

func (*ValidatorIntP[T]) Context

func (validator *ValidatorIntP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorIntP[T]) EqualTo

func (validator *ValidatorIntP[T]) EqualTo(value T, template ...string) *ValidatorIntP[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := int(2)
Is(v.IntP(&quantity).EqualTo(2))

func (*ValidatorIntP[T]) GreaterOrEqualTo

func (validator *ValidatorIntP[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorIntP[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := int(3)
Is(v.IntP(&quantity).GreaterOrEqualTo(3))

func (*ValidatorIntP[T]) GreaterThan

func (validator *ValidatorIntP[T]) GreaterThan(value T, template ...string) *ValidatorIntP[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := int(3)
Is(v.IntP(&quantity).GreaterThan(2))

func (*ValidatorIntP[T]) InSlice

func (validator *ValidatorIntP[T]) InSlice(slice []T, template ...string) *ValidatorIntP[T]

Validate if a number is present in a numeric slice. For example:

quantity := int(3)
validQuantities := []int{1,3,5}
Is(v.IntP(&quantity).InSlice(validQuantities))

func (*ValidatorIntP[T]) LessOrEqualTo

func (validator *ValidatorIntP[T]) LessOrEqualTo(value T, template ...string) *ValidatorIntP[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := int(2)
Is(v.IntP(&quantity).LessOrEqualTo(2))

func (*ValidatorIntP[T]) LessThan

func (validator *ValidatorIntP[T]) LessThan(value T, template ...string) *ValidatorIntP[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := int(2)
Is(v.IntP(&quantity).LessThan(3))

func (*ValidatorIntP[T]) Negative added in v0.7.0

func (validator *ValidatorIntP[T]) Negative(template ...string) *ValidatorIntP[T]

Validate if a numeric value is negative (less than zero).

For example:

n := int(-5)
Is(v.IntP(&n).Negative())

func (*ValidatorIntP[T]) Nil

func (validator *ValidatorIntP[T]) Nil(template ...string) *ValidatorIntP[T]

Validate if a numeric pointer value is nil.

For example:

var n *int
Is(v.IntP(n).Nil())

func (*ValidatorIntP[T]) Not

func (validator *ValidatorIntP[T]) Not() *ValidatorIntP[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
n := int(0)
Is(v.IntP(&n).Not().Zero()).Valid()

func (*ValidatorIntP[T]) Or added in v0.3.0

func (validator *ValidatorIntP[T]) Or() *ValidatorIntP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := int(0)
isValid := v.Is(v.IntP(&input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorIntP[T]) Passing

func (validator *ValidatorIntP[T]) Passing(function func(v *T) bool, template ...string) *ValidatorIntP[T]

Validate if a numeric value passes a custom function. For example:

quantity := int(2)
Is(v.IntP(&quantity).Passing((v *int) bool {
	return *v == getAllowedQuantity()
})

func (*ValidatorIntP[T]) Positive added in v0.7.0

func (validator *ValidatorIntP[T]) Positive(template ...string) *ValidatorIntP[T]

Validate if a numeric value is positive (greater than zero).

For example:

n := int(5)
Is(v.IntP(&n).Positive())

func (*ValidatorIntP[T]) Zero

func (validator *ValidatorIntP[T]) Zero(template ...string) *ValidatorIntP[T]

Validate if a numeric value is zero.

For example:

n := int(0)
Is(v.IntP(&n).Zero())

func (*ValidatorIntP[T]) ZeroOrNil

func (validator *ValidatorIntP[T]) ZeroOrNil(template ...string) *ValidatorIntP[T]

Validate if a numeric value is zero or nil.

For example:

n := int(0)
Is(v.IntP(&n).ZeroOrNil())

var n *int
Is(v.IntP(n).ZeroOrNil())

type ValidatorNumber

type ValidatorNumber[T TypeNumber] struct {
	// contains filtered or unexported fields
}

The ValidatorNumber provides functions for setting validation rules for a TypeNumber value type, or a custom type based on a TypeNumber.

TypeNumber is a generic interface defined by Valgo that generalizes any standard Golang type.

func Number

func Number[T TypeNumber](value T, nameAndTitle ...string) *ValidatorNumber[T]

func (*ValidatorNumber[T]) Between

func (validator *ValidatorNumber[T]) Between(min T, max T, template ...string) *ValidatorNumber[T]

Validate if a number is within a range (inclusive). For example:

Is(v.Number(3).Between(2,6))

func (*ValidatorNumber[T]) Context

func (validator *ValidatorNumber[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorNumber[T]) EqualTo

func (validator *ValidatorNumber[T]) EqualTo(value T, template ...string) *ValidatorNumber[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := 2
Is(v.Number(quantity).Equal(2))

func (*ValidatorNumber[T]) GreaterOrEqualTo

func (validator *ValidatorNumber[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorNumber[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := 3
Is(v.Number(quantity).GreaterOrEqualTo(3))

func (*ValidatorNumber[T]) GreaterThan

func (validator *ValidatorNumber[T]) GreaterThan(value T, template ...string) *ValidatorNumber[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := 3
Is(v.Number(quantity).GreaterThan(2))

func (*ValidatorNumber[T]) InSlice

func (validator *ValidatorNumber[T]) InSlice(slice []T, template ...string) *ValidatorNumber[T]

Validate if a number is present in a numeric slice. For example:

quantity := 3
validQuantities := []int{1,3,5}
Is(v.Number(quantity).InSlice(validQuantities))

func (*ValidatorNumber[T]) LessOrEqualTo

func (validator *ValidatorNumber[T]) LessOrEqualTo(value T, template ...string) *ValidatorNumber[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := 2
Is(v.Number(quantity).LessOrEqualTo(2))

func (*ValidatorNumber[T]) LessThan

func (validator *ValidatorNumber[T]) LessThan(value T, template ...string) *ValidatorNumber[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := 2
Is(v.Number(quantity).LessThan(3))

func (*ValidatorNumber[T]) Not

func (validator *ValidatorNumber[T]) Not() *ValidatorNumber[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
Is(v.Number(0).Not().Zero()).Valid()

func (*ValidatorNumber[T]) Or added in v0.3.0

func (validator *ValidatorNumber[T]) Or() *ValidatorNumber[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := 0
isValid := v.Is(v.Number(input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorNumber[T]) Passing

func (validator *ValidatorNumber[T]) Passing(function func(v T) bool, template ...string) *ValidatorNumber[T]

Validate if a numeric value passes a custom function. For example:

quantity := 2
Is(v.Number(quantity).Passing((v int) bool {
	return v == getAllowedQuantity()
})

func (*ValidatorNumber[T]) Zero

func (validator *ValidatorNumber[T]) Zero(template ...string) *ValidatorNumber[T]

Validate if a numeric value is zero.

For example:

Is(v.Number(0).Zero())

type ValidatorNumberP

type ValidatorNumberP[T TypeNumber] struct {
	// contains filtered or unexported fields
}

The Numeric pointer validator type that keeps its validator context.

func NumberP

func NumberP[T TypeNumber](value *T, nameAndTitle ...string) *ValidatorNumberP[T]

Receives a numeric pointer to validate.

The value can be any golang numeric pointer type (*int64, *int32, *float32, *uint, etc.) or a custom numeric type such as `type Level *int32;`

Optionally, the function can receive a name and title, in that order, to be used in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorNumberP[T]) Between

func (validator *ValidatorNumberP[T]) Between(min T, max T, template ...string) *ValidatorNumberP[T]

Validate if the value of a numeric pointer is within a range (inclusive). For example:

n := 3
Is(v.NumberP(&n).Between(2,6))

func (*ValidatorNumberP[T]) Context

func (validator *ValidatorNumberP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorNumberP[T]) EqualTo

func (validator *ValidatorNumberP[T]) EqualTo(value T, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is equal to another value. This function internally uses the golang `==` operator. For example:

quantity := 2
Is(v.NumberP(quantity).Equal(2))

func (*ValidatorNumberP[T]) GreaterOrEqualTo

func (validator *ValidatorNumberP[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is greater than or equal to another value. This function internally uses the golang `>=` operator. For example:

quantity := 3
Is(v.NumberP(&quantity).GreaterOrEqualTo(3))

func (*ValidatorNumberP[T]) GreaterThan

func (validator *ValidatorNumberP[T]) GreaterThan(value T, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is greater than another value. This function internally uses the golang `>` operator. For example:

quantity := 3
Is(v.NumberP(&quantity).GreaterThan(2))

func (*ValidatorNumberP[T]) InSlice

func (validator *ValidatorNumberP[T]) InSlice(slice []T, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is present in a numeric slice. For example:

quantity := 3
validQuantities := []int{1,3,5}
Is(v.NumberP(&quantity).InSlice(validQuantities))

func (*ValidatorNumberP[T]) LessOrEqualTo

func (validator *ValidatorNumberP[T]) LessOrEqualTo(value T, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is less than or equal to another value. This function internally uses the golang `<=` operator. For example:

quantity := 2
Is(v.NumberP(&quantity).LessOrEqualTo(2))

func (*ValidatorNumberP[T]) LessThan

func (validator *ValidatorNumberP[T]) LessThan(value T, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is less than another value. This function internally uses the golang `<` operator. For example:

quantity := 2
Is(v.NumberP(&quantity).LessThan(3))

func (*ValidatorNumberP[T]) Nil

func (validator *ValidatorNumberP[T]) Nil(template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is nil.

For example:

var quantity *int
Is(v.NumberP(quantity).Nil()) // Will be true

func (*ValidatorNumberP[T]) Not

func (validator *ValidatorNumberP[T]) Not() *ValidatorNumberP[T]

Invert the boolean value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
n := 0
Is(v.NumberP(&n).Not().Zero()).Valid()

func (*ValidatorNumberP[T]) Or added in v0.3.0

func (validator *ValidatorNumberP[T]) Or() *ValidatorNumberP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := 0
isValid := v.Is(v.NumberP(&input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorNumberP[T]) Passing

func (validator *ValidatorNumberP[T]) Passing(function func(v *T) bool, template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value passes a custom function. For example:

quantity := 2
Is(v.NumberP(&quantity).Passing((v *int) bool {
	return *v == getAllowedQuantity()
})

func (*ValidatorNumberP[T]) Zero

func (validator *ValidatorNumberP[T]) Zero(template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is zero.

For example:

n := 0
Is(v.NumberP(&n).Zero())

func (*ValidatorNumberP[T]) ZeroOrNil

func (validator *ValidatorNumberP[T]) ZeroOrNil(template ...string) *ValidatorNumberP[T]

Validate if a numeric pointer value is zero or nil.

For example:

var _quantity *int
Is(v.NumberP(_quantity).ZeroOrNil()) // Will be true

type ValidatorString

type ValidatorString[T ~string] struct {
	// contains filtered or unexported fields
}

The `ValidatorString` provides functions for setting validation rules for a string value type, or a custom type based on a string.

func String

func String[T ~string](value T, nameAndTitle ...string) *ValidatorString[T]

func (*ValidatorString[T]) Between

func (validator *ValidatorString[T]) Between(min T, max T, template ...string) *ValidatorString[T]

Validate if the value of a string is within a range (inclusive). For example:

slug := "ab"
Is(v.String(slug).Between("ab","ac"))

func (*ValidatorString[T]) Blank

func (validator *ValidatorString[T]) Blank(template ...string) *ValidatorString[T]

Validate if a string value is blank. Blank will be true if the length of the string is zero or if the string only has spaces. For example:

Is(v.String("").Empty()) // Will be true
Is(v.String(" ").Empty()) // Will be true

func (*ValidatorString[T]) Context

func (validator *ValidatorString[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorString[T]) Empty

func (validator *ValidatorString[T]) Empty(template ...string) *ValidatorString[T]

Validate if a string value is empty. Return false if the length of the string is greater than zero, even if the string has only spaces.

For checking if the string has only spaces, use the function `Blank()` instead. For example:

Is(v.String("").Empty()) // Will be true
Is(v.String(" ").Empty()) // Will be false

func (*ValidatorString[T]) EqualTo

func (validator *ValidatorString[T]) EqualTo(value T, template ...string) *ValidatorString[T]

Validate if a string value is equal to another. This function internally uses the golang `==` operator. For example:

status := "running"
Is(v.String(status).Equal("running"))

func (*ValidatorString[T]) GreaterOrEqualTo

func (validator *ValidatorString[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorString[T]

Validate if a string value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

section := "bc"
Is(v.String(section).GreaterOrEqualTo("bc"))

func (*ValidatorString[T]) GreaterThan

func (validator *ValidatorString[T]) GreaterThan(value T, template ...string) *ValidatorString[T]

Validate if a string value is greater than another. This function internally uses the golang `>` operator. For example:

section := "bb"
Is(v.String(section).GreaterThan("ba"))

func (*ValidatorString[T]) InSlice

func (validator *ValidatorString[T]) InSlice(slice []T, template ...string) *ValidatorString[T]

Validate if a string is present in a string slice. For example:

status := "idle"
validStatus := []string{"idle", "paused", "stopped"}
Is(v.String(status).InSlice(validStatus))

func (*ValidatorString[T]) LessOrEqualTo

func (validator *ValidatorString[T]) LessOrEqualTo(value T, template ...string) *ValidatorString[T]

Validate if a string value is less than or equal to another. This function internally uses the golang `<=` operator to compare two strings. For example:

section := "bc"
Is(v.String(section).LessOrEqualTo("bc"))

func (*ValidatorString[T]) LessThan

func (validator *ValidatorString[T]) LessThan(value T, template ...string) *ValidatorString[T]

Validate if a string value is less than another. This function internally uses the golang `<` operator. For example:

section := "bb"
Is(v.String(section).LessThan("bc"))

func (*ValidatorString[T]) MatchingTo

func (validator *ValidatorString[T]) MatchingTo(regex *regexp.Regexp, template ...string) *ValidatorString[T]

Validate if a string matches a regular expression. For example:

status := "pre-approved"
regex, _ := regexp.Compile("pre-.+")
Is(v.String(status).MatchingTo(regex))

func (*ValidatorString[T]) MaxBytes added in v0.6.0

func (validator *ValidatorString[T]) MaxBytes(length int, template ...string) *ValidatorString[T]

Validate the maximum length (in bytes) of a string. For example:

slug := "myname"
Is(v.String(slug).MaxBytes(6))

For character count, use `MaxLength` instead.

func (*ValidatorString[T]) MaxLength

func (validator *ValidatorString[T]) MaxLength(length int, template ...string) *ValidatorString[T]

Validate the maximum length (in runes/characters) of a string. For example:

word := "虎視眈々" // 4 runes, len(word) = 12 bytes
Is(v.String(word).MaxLength(4))

func (*ValidatorString[T]) MinBytes added in v0.6.0

func (validator *ValidatorString[T]) MinBytes(length int, template ...string) *ValidatorString[T]

Validate the minimum length (in bytes) of a string. For example:

slug := "myname"
Is(v.String(slug).MinBytes(6))

For character count, use `MinLength` instead.

func (*ValidatorString[T]) MinLength

func (validator *ValidatorString[T]) MinLength(length int, template ...string) *ValidatorString[T]

Validate the minimum length (in runes/characters) of a string. For example:

word := "虎視眈々" // 4 runes, len(word) = 12 bytes
Is(v.String(word).MinLength(4))

func (*ValidatorString[T]) Not

func (validator *ValidatorString[T]) Not() *ValidatorString[T]

Invert the boolean value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Blank() function
Is(v.String("").Not().Blank()).Valid()

func (*ValidatorString[T]) OfByteLength added in v0.6.0

func (validator *ValidatorString[T]) OfByteLength(length int, template ...string) *ValidatorString[T]

Validate the length (in bytes) of a string. For example:

slug := "myname"
Is(v.String(slug).OfByteLength(6))

For character count, use `OfLength` instead.

func (*ValidatorString[T]) OfByteLengthBetween added in v0.6.0

func (validator *ValidatorString[T]) OfByteLengthBetween(min int, max int, template ...string) *ValidatorString[T]

Validate if the length (in bytes) of a string is within a range (inclusive). For example:

slug := "myname"
Is(v.String(slug).OfByteLengthBetween(2,6))

For character count, use `OfLengthBetween` instead.

func (*ValidatorString[T]) OfLength

func (validator *ValidatorString[T]) OfLength(length int, template ...string) *ValidatorString[T]

Validate the length (in runes/characters) of a string. For example:

word := "虎視眈々" // 4 runes, len(word) = 12 bytes
Is(v.String(word).OfLength(4))

func (*ValidatorString[T]) OfLengthBetween

func (validator *ValidatorString[T]) OfLengthBetween(min int, max int, template ...string) *ValidatorString[T]

Validate if the length (in runes/characters) of a string is within a range (inclusive). For example:

word := "虎視眈々" // 4 runes, len(word) = 12 bytes
Is(v.String(word).OfLengthBetween(2,4))

func (*ValidatorString[T]) Or added in v0.3.0

func (validator *ValidatorString[T]) Or() *ValidatorString[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the string is equals "test".
input := "test"
isValid := v.Is(v.String(input).MinLength(5).Or().EqualTo("test")).Valid()

func (*ValidatorString[T]) Passing

func (validator *ValidatorString[T]) Passing(function func(v0 T) bool, template ...string) *ValidatorString[T]

Validate if a string value passes a custom function. For example:

status := ""
Is(v.String(status).Passing((v string) bool {
	return v == getNewStatus()
})

type ValidatorStringP

type ValidatorStringP[T ~string] struct {
	// contains filtered or unexported fields
}

The String pointer validator type that keeps its validator context.

func StringP

func StringP[T ~string](value *T, nameAndTitle ...string) *ValidatorStringP[T]

func (*ValidatorStringP[T]) Between

func (validator *ValidatorStringP[T]) Between(min T, max T, template ...string) *ValidatorStringP[T]

Validate if the value of a string pointer's value is in a range (inclusive). For example:

slug := "ab"
Is(v.StringP(&slug).Between("ab","ac"))

func (*ValidatorStringP[T]) Blank

func (validator *ValidatorStringP[T]) Blank(template ...string) *ValidatorStringP[T]

Validate if a string value is blank. Blank will be true if the length of the string is zero or if the string only has spaces. For example:

status := ""
Is(v.StringP(&status).Blank()) // Will be true
status = " "
Is(v.StringP(&status).Blank()) // Will be true

func (*ValidatorStringP[T]) BlankOrNil

func (validator *ValidatorStringP[T]) BlankOrNil(template ...string) *ValidatorStringP[T]

Validate if a string value is blank or nil. Blank will be true if the length of the string is zero or if the string only has spaces. For example:

status := ""
Is(v.StringP(&status).BlankOrNil()) // Will be true
status = " "
Is(v.StringP(&status).BlankOrNil()) // Will be true
var _status *string
Is(v.StringP(_status).BlankOrNil()) // Will be true

func (*ValidatorStringP[T]) Context

func (validator *ValidatorStringP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorStringP[T]) Empty

func (validator *ValidatorStringP[T]) Empty(template ...string) *ValidatorStringP[T]

Validate if a string value is empty. Empty will be false if the length of the string is greater than zero, even if the string has only spaces. For checking if the string has only spaces, uses the function `Blank()` instead. For example:

status := ""
Is(v.StringP(&status).Empty()) // Will be true
status = " "
Is(v.StringP(&status).Empty()) // Will be false

func (*ValidatorStringP[T]) EmptyOrNil

func (validator *ValidatorStringP[T]) EmptyOrNil(template ...string) *ValidatorStringP[T]

Validate if a string value is empty or nil. Empty will be false if the length of the string is greater than zero, even if the string has only spaces. For checking if the string has only spaces, uses the function `BlankOrNil()` instead. For example:

status := ""
Is(v.StringP(&status).EmptyOrNil()) // Will be true
status = " "
Is(v.StringP(&status).EmptyOrNil()) // Will be false
var _status *string
Is(v.StringP(_status).EmptyOrNil()) // Will be true

func (*ValidatorStringP[T]) EqualTo

func (validator *ValidatorStringP[T]) EqualTo(value T, template ...string) *ValidatorStringP[T]

Validate if the value of a string pointer is equal to a another value. For example:

status := "running"
Is(v.StringP(&status).Equal("running"))

func (*ValidatorStringP[T]) GreaterOrEqualTo

func (validator *ValidatorStringP[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorStringP[T]

func (*ValidatorStringP[T]) GreaterThan

func (validator *ValidatorStringP[T]) GreaterThan(value T, template ...string) *ValidatorStringP[T]

Validate if a string value is greater than another. This function internally uses the golang `>` operator. For example:

section := "bb"
Is(v.StringP(&section).GreaterThan("ba"))

func (*ValidatorStringP[T]) InSlice

func (validator *ValidatorStringP[T]) InSlice(slice []T, template ...string) *ValidatorStringP[T]

Validate if the value of a string pointer is present in a string slice. For example:

status := "idle"
validStatus := []string{"idle", "paused", "stopped"}
Is(v.StringP(&status).InSlice(validStatus))

func (*ValidatorStringP[T]) LessOrEqualTo

func (validator *ValidatorStringP[T]) LessOrEqualTo(value T, template ...string) *ValidatorStringP[T]

Validate if a string value is less or equal to another. This function internally uses the golang `<=` operator to compare two strings. For example:

section := "bc"
Is(v.StringP(&section).LessOrEqualTo("bc"))

func (*ValidatorStringP[T]) LessThan

func (validator *ValidatorStringP[T]) LessThan(value T, template ...string) *ValidatorStringP[T]

Validate if a string value is less than another. This function internally uses the golang `<` operator. For example:

section := "bb"
Is(v.StringP(&section).LessThan("bc"))

func (*ValidatorStringP[T]) MatchingTo

func (validator *ValidatorStringP[T]) MatchingTo(regex *regexp.Regexp, template ...string) *ValidatorStringP[T]

Validate if the value of a string pointer match a regular expression. For example:

status := "pre-approved"
regex, _ := regexp.Compile("pre-.+")
Is(v.StringP(&status).MatchingTo(regex))

func (*ValidatorStringP[T]) MaxBytes added in v0.6.0

func (validator *ValidatorStringP[T]) MaxBytes(length int, template ...string) *ValidatorStringP[T]

Validate the maximum length (in bytes) of a string pointer's value. For example:

slug := "myname"
Is(v.StringP(&slug).MaxBytes(6))

For character count, use `MaxLength` instead.

func (*ValidatorStringP[T]) MaxLength

func (validator *ValidatorStringP[T]) MaxLength(length int, template ...string) *ValidatorStringP[T]

Validate the maximum length (in runes/characters) of a string pointer's value. For example:

slug := "虎視眈々" // 4 runes, len(slug) = 12 bytes
Is(v.StringP(&slug).MaxLength(4))

func (*ValidatorStringP[T]) MinBytes added in v0.6.0

func (validator *ValidatorStringP[T]) MinBytes(length int, template ...string) *ValidatorStringP[T]

Validate the minimum length (in bytes) of a string pointer's value. For example:

slug := "myname"
Is(v.StringP(&slug).MinBytes(6))

For character count, use `MinLength` instead.

func (*ValidatorStringP[T]) MinLength

func (validator *ValidatorStringP[T]) MinLength(length int, template ...string) *ValidatorStringP[T]

Validate the minimum length (in runes/characters) of a string pointer's value. For example:

slug := "虎視眈々" // 4 runes, len(slug) = 12 bytes
Is(v.StringP(&slug).MinLength(4))

func (*ValidatorStringP[T]) Nil

func (validator *ValidatorStringP[T]) Nil(template ...string) *ValidatorStringP[T]

Validate if a string pointer is nil. For example:

var status *string
Is(v.StringP(status).Nil())

func (*ValidatorStringP[T]) Not

func (validator *ValidatorStringP[T]) Not() *ValidatorStringP[T]

Invert the logical value associated to the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Blank() function
status := ""
Is(v.StringP(&status).Not().Blank()).Valid()

func (*ValidatorStringP[T]) OfByteLength added in v0.6.0

func (validator *ValidatorStringP[T]) OfByteLength(length int, template ...string) *ValidatorStringP[T]

Validate the length (in bytes) of a string pointer's value. For example:

slug := "myname"
Is(v.StringP(&slug).OfByteLength(6))

For character count, use `OfLength` instead.

func (*ValidatorStringP[T]) OfByteLengthBetween added in v0.6.0

func (validator *ValidatorStringP[T]) OfByteLengthBetween(min int, max int, template ...string) *ValidatorStringP[T]

Validate if the length (in bytes) of a string pointer's value is in a range (inclusive). For example:

slug := "myname"
Is(v.StringP(&slug).OfByteLengthBetween(2,6))

For character count, use `OfLengthBetween` instead.

func (*ValidatorStringP[T]) OfLength

func (validator *ValidatorStringP[T]) OfLength(length int, template ...string) *ValidatorStringP[T]

Validate the length (in runes/characters) of a string pointer's value. For example:

slug := "虎視眈々" // 4 runes, len(slug) = 12 bytes
Is(v.StringP(&slug).OfLength(4))

func (*ValidatorStringP[T]) OfLengthBetween

func (validator *ValidatorStringP[T]) OfLengthBetween(min int, max int, template ...string) *ValidatorStringP[T]

Validate if the length (in runes/characters) of a string pointer's value is in a range (inclusive). For example:

slug := "虎視眈々" // 4 runes, len(slug) = 12 bytes
Is(v.StringP(&slug).OfLengthBetween(2,4))

func (*ValidatorStringP[T]) Or added in v0.3.0

func (validator *ValidatorStringP[T]) Or() *ValidatorStringP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the string is equals "test".
input := "test"
isValid := v.Is(v.StringP(&input).MinLength(5).Or().EqualTo("test")).Valid()

func (*ValidatorStringP[T]) Passing

func (validator *ValidatorStringP[T]) Passing(function func(v0 *T) bool, template ...string) *ValidatorStringP[T]

Validate if a string pointer pass a custom function. For example:

status := ""
Is(v.StringP(&status).Passing((v string) bool {
	return v == getNewStatus()
})

type ValidatorTime added in v0.3.0

type ValidatorTime struct {
	// contains filtered or unexported fields
}

The `ValidatorTime` structure provides a set of methods to perform validation checks on time.Time values, utilizing Go's native time package.

func Time added in v0.3.0

func Time(value time.Time, nameAndTitle ...string) *ValidatorTime

The Time function initiates a new `ValidatorTime` instance to validate a given time value. The optional name and title parameters can be used for enhanced error reporting. If a name is provided without a title, the name is humanized to be used as the title.

For example:

startTime := time.Now()
v := ValidatorTime{}
v.Time(startTime, "start_time", "Start Time")

func (*ValidatorTime) After added in v0.3.0

func (validator *ValidatorTime) After(value time.Time, template ...string) *ValidatorTime

The After method checks if the time value is after a specified time.

For example:

startTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
endTime := time.Date(2023, 1, 1, 1, 0, 0, 0, time.UTC)
Is(v.Time(endTime).After(startTime)).Valid()

func (*ValidatorTime) AfterOrEqualTo added in v0.3.0

func (validator *ValidatorTime) AfterOrEqualTo(value time.Time, template ...string) *ValidatorTime

The AfterOrEqualTo method checks if the time value is either after or equal to a specified time.

For example:

timeA := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
timeB := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
Is(v.Time(timeA).AfterOrEqualTo(timeB)).Valid()

func (*ValidatorTime) Before added in v0.3.0

func (validator *ValidatorTime) Before(value time.Time, template ...string) *ValidatorTime

The Before method checks if the time value is before a specified time.

For example:

startTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
endTime := time.Date(2023, 1, 1, 1, 0, 0, 0, time.UTC)
Is(v.Time(startTime).Before(endTime)).Valid()

func (*ValidatorTime) BeforeOrEqualTo added in v0.3.0

func (validator *ValidatorTime) BeforeOrEqualTo(value time.Time, template ...string) *ValidatorTime

The BeforeOrEqualTo method checks if the time value is either before or equal to a specified time.

For example:

timeA := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
timeB := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
Is(v.Time(timeA).BeforeOrEqualTo(timeB)).Valid()

func (*ValidatorTime) Between added in v0.3.0

func (validator *ValidatorTime) Between(min time.Time, max time.Time, template ...string) *ValidatorTime

The Between method verifies if the time value falls within a given time range, inclusive.

For example:

minTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
maxTime := time.Date(2023, 1, 1, 12, 0, 0, 0, time.UTC)
checkTime := time.Date(2023, 1, 1, 6, 0, 0, 0, time.UTC)
Is(v.Time(checkTime).Between(minTime, maxTime)).Valid()

func (*ValidatorTime) Context added in v0.3.0

func (validator *ValidatorTime) Context() *ValidatorContext

The Context method returns the current context of the validator, which can be utilized to create custom validations by extending this validator.

func (*ValidatorTime) EqualTo added in v0.3.0

func (validator *ValidatorTime) EqualTo(value time.Time, template ...string) *ValidatorTime

The EqualTo method validates if the time value is equal to another given time value. It uses the equality (`==`) operator from Go for the comparison.

For example:

timeA := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
timeB := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
Is(v.Time(timeA).EqualTo(timeB)).Valid()

func (*ValidatorTime) InSlice added in v0.3.0

func (validator *ValidatorTime) InSlice(slice []time.Time, template ...string) *ValidatorTime

The InSlice method validates if the time value is found within a provided slice of time values.

For example:

timeA := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
timeB := time.Date(2023, 1, 1, 1, 0, 0, 0, time.UTC)
timeSlice := []time.Time{timeA, timeB}
checkTime := time.Date(2023, 1, 1, 1, 0, 0, 0, time.UTC)
Is(v.Time(checkTime).InSlice(timeSlice)).Valid()

func (*ValidatorTime) Not added in v0.3.0

func (validator *ValidatorTime) Not() *ValidatorTime

The Not method inverts the boolean value associated with the next validator method. This can be used to negate the check performed by the next validation method in the chain.

For example:

// Will return false because Not() inverts the boolean value of the Zero() function
startTime := time.Now()
Is(v.Time(startTime).Not().Zero()).Valid()

func (*ValidatorTime) Or added in v0.3.0

func (validator *ValidatorTime) Or() *ValidatorTime

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the time is before or equal to time.Now().
t := time.Now()
isValid := v.Is(v.Time(t).Zero().Or().BeforeOrEqualTo(time.Now())).Valid()

func (*ValidatorTime) Passing added in v0.3.0

func (validator *ValidatorTime) Passing(function func(v0 time.Time) bool, template ...string) *ValidatorTime

The Passing method allows for custom validation logic by accepting a function that returns a boolean indicating whether the validation passed or failed.

For example:

checkTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
Is(v.Time(checkTime).Passing(func(t time.Time) bool {
    return t.Year() == 2023
})).Valid()

func (*ValidatorTime) Zero added in v0.3.0

func (validator *ValidatorTime) Zero(template ...string) *ValidatorTime

The Zero method verifies if the time value is a zero time, which means it hasn't been initialized yet.

For example:

zeroTime := time.Time{}
Is(v.Time(zeroTime).Zero()).Valid()

type ValidatorTimeP added in v0.3.0

type ValidatorTimeP struct {
	// contains filtered or unexported fields
}

ValidatorTimeP is a type that facilitates validation for time pointer variables. It retains a context that records details about the validation process.

func TimeP added in v0.3.0

func TimeP(value *time.Time, nameAndTitle ...string) *ValidatorTimeP

TimeP initializes a new ValidatorTimeP instance with the provided time pointer and optional name and title arguments for detailed error messages.

Usage example:

var myTime *time.Time
v.TimeP(myTime, "start_time", "Start Time")

func (*ValidatorTimeP) After added in v0.3.0

func (validator *ValidatorTimeP) After(value time.Time, template ...string) *ValidatorTimeP

After validates that the time pointer is after the specified time value.

Usage example:

t1 := time.Now()
t2 := t1.Add(-time.Hour)
Is(v.TimeP(&t1).After(t2)).Valid()  // Will return true.

func (*ValidatorTimeP) AfterOrEqualTo added in v0.3.0

func (validator *ValidatorTimeP) AfterOrEqualTo(value time.Time, template ...string) *ValidatorTimeP

AfterOrEqualTo validates that the time pointer is after or equal to the specified time value.

Usage example:

t1 := time.Now()
t2 := t1
Is(v.TimeP(&t1).AfterOrEqualTo(t2)).Valid()  // Will return true.

func (*ValidatorTimeP) Before added in v0.3.0

func (validator *ValidatorTimeP) Before(value time.Time, template ...string) *ValidatorTimeP

Before validates that the time pointer is before the specified time value.

Usage example:

t1 := time.Now()
t2 := t1.Add(time.Hour)
Is(v.TimeP(&t1).Before(t2)).Valid()  // Will return true.

func (*ValidatorTimeP) BeforeOrEqualTo added in v0.3.0

func (validator *ValidatorTimeP) BeforeOrEqualTo(value time.Time, template ...string) *ValidatorTimeP

BeforeOrEqualTo validates that the time pointer is before or equal to the specified time value.

Usage example:

t1 := time.Now()
t2 := t1
Is(v.TimeP(&t1).BeforeOrEqualTo(t2)).Valid()  // Will return true.

func (*ValidatorTimeP) Between added in v0.3.0

func (validator *ValidatorTimeP) Between(min time.Time, max time.Time, template ...string) *ValidatorTimeP

Between validates that the time pointer is between the specified minimum and maximum time values (inclusive).

Usage example:

t1 := time.Now()
min := t1.Add(-time.Hour)
max := t1.Add(time.Hour)
Is(v.TimeP(&t1).Between(min, max)).Valid()  // Will return true.

func (*ValidatorTimeP) Context added in v0.3.0

func (validator *ValidatorTimeP) Context() *ValidatorContext

Context retrieves the context associated with the validator.

func (*ValidatorTimeP) EqualTo added in v0.3.0

func (validator *ValidatorTimeP) EqualTo(value time.Time, template ...string) *ValidatorTimeP

EqualTo validates that the time pointer is equal to the specified time value.

Usage example:

t1 := time.Now()
t2 := t1
Is(v.TimeP(&t1).EqualTo(t2)).Valid()  // Will return true.

func (*ValidatorTimeP) InSlice added in v0.3.0

func (validator *ValidatorTimeP) InSlice(slice []time.Time, template ...string) *ValidatorTimeP

InSlice validates that the time pointer is pointing to a time value present in the specified slice.

Usage example:

t := time.Now()
validTimes := []time.Time{t, time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)}
Is(v.TimeP(&t).InSlice(validTimes)).Valid()  // Will return true.

func (*ValidatorTimeP) Nil added in v0.3.0

func (validator *ValidatorTimeP) Nil(template ...string) *ValidatorTimeP

Nil validates that the time pointer is nil.

Usage example:

var t *time.Time
Is(v.TimeP(t).Nil()).Valid()  // Will return true as t is nil.

func (*ValidatorTimeP) NilOrZero added in v0.3.0

func (validator *ValidatorTimeP) NilOrZero(template ...string) *ValidatorTimeP

NilOrZero validates that the time pointer is either nil or pointing to a zero time value.

Usage example:

var t *time.Time
Is(v.TimeP(t).NilOrZero()).Valid()  // Will return true as t is nil.

func (*ValidatorTimeP) Not added in v0.3.0

func (validator *ValidatorTimeP) Not() *ValidatorTimeP

Not negates the result of the next validator function in the chain.

Usage example:

t := time.Now()
Is(v.TimeP(&t).Not().Zero()).Valid()  // Will return false since t is not a zero time.

func (*ValidatorTimeP) Or added in v0.3.0

func (validator *ValidatorTimeP) Or() *ValidatorTimeP

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the time is before or equal to time.Now().
t := time.Now()
isValid := v.Is(v.TimeP(&t).Nil().Or().BeforeOrEqualTo(time.Now())).Valid()

func (*ValidatorTimeP) Passing added in v0.3.0

func (validator *ValidatorTimeP) Passing(function func(v0 *time.Time) bool, template ...string) *ValidatorTimeP

Passing allows for custom validation function to be applied on the time pointer.

Usage example:

t := time.Now()
Is(v.TimeP(&t).Passing(func(v0 *time.Time) bool { return v0.After(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)) })).Valid()  // Custom validation.

func (*ValidatorTimeP) Zero added in v0.3.0

func (validator *ValidatorTimeP) Zero(template ...string) *ValidatorTimeP

Zero validates that the time pointer is pointing to a zero time value.

Usage example:

var t *time.Time
Is(v.TimeP(t).Zero()).Valid()  // Will return true as t is nil and thus pointing to a zero time.

type ValidatorTyped added in v0.7.0

type ValidatorTyped[T any] struct {
	// contains filtered or unexported fields
}

The Typed validator's type that keeps its validator context. T can be any Go type (pointer, struct, slice, map, etc.).

func Typed added in v0.7.0

func Typed[T any](value T, nameAndTitle ...string) *ValidatorTyped[T]

Receive a value of type T to validate.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A value_%N pattern is used as a name in the error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name phone_number will be humanized as Phone Number.

Example:

v.Is(v.Typed(user).Not().Nil())

func (*ValidatorTyped[T]) Context added in v0.7.0

func (validator *ValidatorTyped[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorTyped[T]) Nil added in v0.7.0

func (validator *ValidatorTyped[T]) Nil(template ...string) *ValidatorTyped[T]

Validate if a value is nil. Works for nil-able kinds: pointers, slices, maps, chans, funcs, and interfaces. For non-nil-able types, this will return false.

For example:

var s *string
v.Is(v.Typed(s).Nil())

func (*ValidatorTyped[T]) Not added in v0.7.0

func (validator *ValidatorTyped[T]) Not() *ValidatorTyped[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because `Not()` inverts the boolean value associated with `EqualTo()`
v.Is(v.Typed("a").Not().EqualTo("a")).Valid()

func (*ValidatorTyped[T]) Or added in v0.7.0

func (validator *ValidatorTyped[T]) Or() *ValidatorTyped[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the string is equals "test".
input := "test"
isValid := v.Is(v.String(input).MinLength(5).Or().EqualTo("test")).Valid()

func (*ValidatorTyped[T]) Passing added in v0.7.0

func (validator *ValidatorTyped[T]) Passing(function func(v T) bool, template ...string) *ValidatorTyped[T]

Validate if a value passes a custom function. The function receives a typed T value, enabling compile-time type safety.

For example:

type Status string
status := Status("running")
isValid := v.Is(
  v.Typed(status).Passing(func(s Status) bool {
    return s == "running" || s == "paused"
  }),
).Valid()

type ValidatorUint added in v0.7.0

type ValidatorUint[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64] struct {
	// contains filtered or unexported fields
}

The ValidatorUint provides functions for setting validation rules for a uint value types, or a custom type based on a uint, uint8, uint16, uint32, or uint64.

func Byte

func Byte[T ~byte](value T, nameAndTitle ...string) *ValidatorUint[T]

Receives an byte value to validate.

The value can also be a custom byte type such as type Age byte.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint added in v0.7.0

func Uint[T ~uint](value T, nameAndTitle ...string) *ValidatorUint[T]

Receives an uint value to validate.

The value can also be a custom uint type such as type Age uint.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint8

func Uint8[T ~uint8](value T, nameAndTitle ...string) *ValidatorUint[T]

Receives an uint8 value to validate.

The value can also be a custom uint8 type such as type Age uint8.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint16

func Uint16[T ~uint16](value T, nameAndTitle ...string) *ValidatorUint[T]

Receives an uint16 value to validate.

The value can also be a custom uint16 type such as type Age uint16.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint32

func Uint32[T ~uint32](value T, nameAndTitle ...string) *ValidatorUint[T]

Receives an uint32 value to validate.

The value can also be a custom uint32 type such as type Age uint32.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint64

func Uint64[T ~uint64](value T, nameAndTitle ...string) *ValidatorUint[T]

Receives an uint64 value to validate.

The value can also be a custom uint64 type such as type Age uint64.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N“ pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorUint[T]) Between added in v0.7.0

func (validator *ValidatorUint[T]) Between(min T, max T, template ...string) *ValidatorUint[T]

Validate if a number is within a range (inclusive). For example:

Is(v.Uint(uint(3)).Between(2,6))

func (*ValidatorUint[T]) Context added in v0.7.0

func (validator *ValidatorUint[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorUint[T]) EqualTo added in v0.7.0

func (validator *ValidatorUint[T]) EqualTo(value T, template ...string) *ValidatorUint[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := uint(2)
Is(v.Uint(quantity).EqualTo(2))

func (*ValidatorUint[T]) GreaterOrEqualTo added in v0.7.0

func (validator *ValidatorUint[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorUint[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := uint(3)
Is(v.Uint(quantity).GreaterOrEqualTo(3))

func (*ValidatorUint[T]) GreaterThan added in v0.7.0

func (validator *ValidatorUint[T]) GreaterThan(value T, template ...string) *ValidatorUint[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := uint(3)
Is(v.Uint(quantity).GreaterThan(2))

func (*ValidatorUint[T]) InSlice added in v0.7.0

func (validator *ValidatorUint[T]) InSlice(slice []T, template ...string) *ValidatorUint[T]

Validate if a number is present in a numeric slice. For example:

quantity := uint(3)
validQuantities := []uint{1,3,5}
Is(v.Uint(quantity).InSlice(validQuantities))

func (*ValidatorUint[T]) LessOrEqualTo added in v0.7.0

func (validator *ValidatorUint[T]) LessOrEqualTo(value T, template ...string) *ValidatorUint[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := uint(2)
Is(v.Uint(quantity).LessOrEqualTo(2))

func (*ValidatorUint[T]) LessThan added in v0.7.0

func (validator *ValidatorUint[T]) LessThan(value T, template ...string) *ValidatorUint[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := uint(2)
Is(v.Uint(quantity).LessThan(3))

func (*ValidatorUint[T]) Not added in v0.7.0

func (validator *ValidatorUint[T]) Not() *ValidatorUint[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
Is(v.Uint(0).Not().Zero()).Valid()

func (*ValidatorUint[T]) Or added in v0.7.0

func (validator *ValidatorUint[T]) Or() *ValidatorUint[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := uint(0)
isValid := v.Is(v.Uint(input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorUint[T]) Passing added in v0.7.0

func (validator *ValidatorUint[T]) Passing(function func(v T) bool, template ...string) *ValidatorUint[T]

Validate if a numeric value passes a custom function. For example:

quantity := uint(2)
Is(v.Uint(quantity).Passing((v uint) bool {
	return v == getAllowedQuantity()
})

func (*ValidatorUint[T]) Zero added in v0.7.0

func (validator *ValidatorUint[T]) Zero(template ...string) *ValidatorUint[T]

Validate if a numeric value is zero.

For example:

Is(v.Uint(uint(0)).Zero())

type ValidatorUintP added in v0.7.0

type ValidatorUintP[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64] struct {
	// contains filtered or unexported fields
}

The ValidatorUintP provides functions for setting validation rules for a uint pointer value types, or a custom type based on a uint, uint8, uint16, uint32, or uint64 pointer.

func ByteP

func ByteP[T ~byte](value *T, nameAndTitle ...string) *ValidatorUintP[T]

Receives a byte pointer value to validate.

The value can also be a custom byte pointer type such as type Age *byte.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint8P

func Uint8P[T ~uint8](value *T, nameAndTitle ...string) *ValidatorUintP[T]

Receives an uint8 pointer value to validate.

The value can also be a custom uint8 pointer type such as type Age *uint8.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint16P

func Uint16P[T ~uint16](value *T, nameAndTitle ...string) *ValidatorUintP[T]

Receives an uint16 pointer value to validate.

The value can also be a custom uint16 pointer type such as type Age *uint16.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint32P

func Uint32P[T ~uint32](value *T, nameAndTitle ...string) *ValidatorUintP[T]

Receives an uint32 pointer value to validate.

The value can also be a custom uint32 pointer type such as type Age *uint32.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func Uint64P

func Uint64P[T ~uint64](value *T, nameAndTitle ...string) *ValidatorUintP[T]

Receives an uint64 pointer value to validate.

The value can also be a custom uint64 pointer type such as type Age *uint64.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func UintP added in v0.7.0

func UintP[T ~uint](value *T, nameAndTitle ...string) *ValidatorUintP[T]

Receives an uint pointer value to validate.

The value can also be a custom uint pointer type such as type Age *uint.

Optionally, the function can receive a name and title, in that order, to be displayed in the error messages. A `value_%N" pattern is used as a name in error messages if a name and title are not supplied; for example: value_0. When the name is provided but not the title, then the name is humanized to be used as the title as well; for example the name `phone_number` will be humanized as `Phone Number`

func (*ValidatorUintP[T]) Between added in v0.7.0

func (validator *ValidatorUintP[T]) Between(min T, max T, template ...string) *ValidatorUintP[T]

Validate if a number is within a range (inclusive). For example:

n := uint(3)
Is(v.UintP(&n).Between(2,6))

func (*ValidatorUintP[T]) Context added in v0.7.0

func (validator *ValidatorUintP[T]) Context() *ValidatorContext

Return the context of the validator. The context is useful to create a custom validator by extending this validator.

func (*ValidatorUintP[T]) EqualTo added in v0.7.0

func (validator *ValidatorUintP[T]) EqualTo(value T, template ...string) *ValidatorUintP[T]

Validate if a numeric value is equal to another. This function internally uses the golang `==` operator. For example:

quantity := uint(2)
Is(v.UintP(&quantity).EqualTo(2))

func (*ValidatorUintP[T]) GreaterOrEqualTo added in v0.7.0

func (validator *ValidatorUintP[T]) GreaterOrEqualTo(value T, template ...string) *ValidatorUintP[T]

Validate if a numeric value is greater than or equal to another. This function internally uses the golang `>=` operator. For example:

quantity := uint(3)
Is(v.UintP(&quantity).GreaterOrEqualTo(3))

func (*ValidatorUintP[T]) GreaterThan added in v0.7.0

func (validator *ValidatorUintP[T]) GreaterThan(value T, template ...string) *ValidatorUintP[T]

Validate if a numeric value is greater than another. This function internally uses the golang `>` operator. For example:

quantity := uint(3)
Is(v.UintP(&quantity).GreaterThan(2))

func (*ValidatorUintP[T]) InSlice added in v0.7.0

func (validator *ValidatorUintP[T]) InSlice(slice []T, template ...string) *ValidatorUintP[T]

Validate if a number is present in a numeric slice. For example:

quantity := uint(3)
validQuantities := []uint{1,3,5}
Is(v.UintP(&quantity).InSlice(validQuantities))

func (*ValidatorUintP[T]) LessOrEqualTo added in v0.7.0

func (validator *ValidatorUintP[T]) LessOrEqualTo(value T, template ...string) *ValidatorUintP[T]

Validate if a numeric value is less than or equal to another. This function internally uses the golang `<=` operator. For example:

quantity := uint(2)
Is(v.UintP(&quantity).LessOrEqualTo(2))

func (*ValidatorUintP[T]) LessThan added in v0.7.0

func (validator *ValidatorUintP[T]) LessThan(value T, template ...string) *ValidatorUintP[T]

Validate if a numeric value is less than another. This function internally uses the golang `<` operator. For example:

quantity := uint(2)
Is(v.UintP(&quantity).LessThan(3))

func (*ValidatorUintP[T]) Nil added in v0.7.0

func (validator *ValidatorUintP[T]) Nil(template ...string) *ValidatorUintP[T]

Validate if a numeric pointer value is nil.

For example:

var n *uint
Is(v.UintP(n).Nil())

func (*ValidatorUintP[T]) Not added in v0.7.0

func (validator *ValidatorUintP[T]) Not() *ValidatorUintP[T]

Invert the logical value associated with the next validator function. For example:

// It will return false because Not() inverts the boolean value associated with the Zero() function
n := uint(0)
Is(v.UintP(&n).Not().Zero()).Valid()

func (*ValidatorUintP[T]) Or added in v0.7.0

func (validator *ValidatorUintP[T]) Or() *ValidatorUintP[T]

Introduces a logical OR in the chain of validation conditions, affecting the evaluation order and priority of subsequent validators. A value passes the validation if it meets any one condition following the Or() call, adhering to a left-to-right evaluation. This mechanism allows for validating against multiple criteria where satisfying any single criterion is sufficient. Example:

// This validator will pass because the input is Zero.
input := uint(0)
isValid := v.Is(v.UintP(&input).GreaterThan(5).Or().Zero()).Valid()

func (*ValidatorUintP[T]) Passing added in v0.7.0

func (validator *ValidatorUintP[T]) Passing(function func(v *T) bool, template ...string) *ValidatorUintP[T]

Validate if a numeric value passes a custom function. For example:

quantity := uint(2)
Is(v.UintP(&quantity).Passing((v *uint) bool {
	return *v == getAllowedQuantity()
})

func (*ValidatorUintP[T]) Zero added in v0.7.0

func (validator *ValidatorUintP[T]) Zero(template ...string) *ValidatorUintP[T]

Validate if a numeric value is zero.

For example:

n := uint(0)
Is(v.UintP(&n).Zero())

func (*ValidatorUintP[T]) ZeroOrNil added in v0.7.0

func (validator *ValidatorUintP[T]) ZeroOrNil(template ...string) *ValidatorUintP[T]

Validate if a numeric value is zero or nil.

For example:

n := uint(0)
Is(v.UintP(&n).ZeroOrNil())

var n *uint
Is(v.UintP(n).ZeroOrNil())

Jump to

Keyboard shortcuts

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