ginvalidator

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2025 License: MIT Imports: 15 Imported by: 0

README

ginvalidator

Overview

ginvalidator is a set of Gin middlewares that wraps the extensive collection of validators and sanitizers offered by my other open source package validatorgo. It also uses the popular open-source package gjson for JSON field syntax, providing efficient querying and extraction of data from JSON objects.

It allows you to combine them in many ways so that you can validate and sanitize your Gin requests, and offers tools to determine if the request is valid or not, which data was matched according to your validators.

It is based on the popular js/express library express-validator

Support

This version of ginvalidator requires that your application is running on Go 1.16+. It's also verified to work with Gin 1.x.x.

Rationale

Why not use?

  • Handwritten Validators: You could write your own validation logic manually, but that gets repetitive and messy fast. Every time you need a new validation, you’re writing the same kind of code over and over. It’s easy to make mistakes, and it’s a pain to maintain.
  • Gin's Built-in Model Binding and Validation: Gin has validation built in, but it’s not ideal for everyone. Struct tags are limiting and make your code harder to read, especially when you need complex rules. Plus, the validation gets tied too tightly to your models, which isn't great for flexibility.
  • Other Libraries (like Galidator): There are other libraries out there, but they often feel too complex for what they do. They require more setup and work than you’d expect, especially when you just want a simple, straightforward solution for validation.

Installation

Make sure you have Go installed on your machine.

Step 1: Create a New Go Module
  1. Create an empty folder with a name of your choice.
  2. Open a terminal, navigate (cd) into that folder, and initialize a new Go module:
go mod init example.com/tutorial
Step 2: Install Required Packages

Use go get to install the necessary packages.

  1. Install Gin:
go get -u github.com/gin-gonic/gin
  1. Install ginvalidator:
go get -u github.com/bube054/ginvalidator

Getting Started

One of the best ways to learn something is by example! So let's roll the sleeves up and get some coding happening.

Setup

The first thing that one needs is a Gin server running. Let's implement one that says hi to someone; for this, create a main.go then add the following code:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/hello", func(ctx *gin.Context) {
        person := ctx.Query("person")
        ctx.String(http.StatusOK, "Hello, %s!", person)
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

Now run this file by executing go run main.go on your terminal.

go run main.go

The HTTP server should be running, and you can open http://localhost:8080/hello?person=John to salute John!

💡 Tip: You can use Air with Go and Gin to implement live reload. This automatically restart the server whenever a file is changed, so you don't have to do this yourself!

Adding a validator

So the server is working, but there are problems with it. Most notably, you don't want to say hello to someone when the person's name is not set. For example, going to http://localhost:8080/hello will print "Hello, ".

That's where ginvalidator and also validatorgo come in handy. ginvalidator provides validators, sanitizers and modifiers that are used to validate your request. validatorgo provides a set of configuration structs to help you customize validators and sanitizers. These structs, like vgo.IsEmptyOpts{IgnoreWhitespace: false}, allow you to fine-tune the behavior of each validation and or sanitization step. By passing these configuration options into chain methods, you can precisely control how the input is processed and validated. Let's add a validator and a modifier that checks that the person query string cannot be empty, with the validator named Empty and modifier named Not:

package main

import (
    "net/http"

    gv "github.com/bube054/ginvalidator"
    vgo "github.com/bube054/validatorgo"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/hello", 
        gv.NewQuery("person", nil).
        Chain().
        Not().
        Empty(&vgo.IsEmptyOpts{IgnoreWhitespace: false}).
        Validate(), func(ctx *gin.Context) {
            person := ctx.Query("person")
            ctx.String(http.StatusOK, "Hello, %s!", person)
        })

    r.Run()
}

📝 Note:
For brevity, gv is used as an alias for ginvalidator and vgo is used as an alias for validatorgo in the code examples.

Now, restart your server, and go to http://localhost:8080/hello again. Hmm, it still prints "Hello, !"... why?

Handling validation errors

ginvalidator validation chain does not report validation errors to users automatically. The reason for this is simple: as you add more validators, or for more fields, how do you want to collect the errors? Do you want a list of all errors, only one per field, only one overall...?

So the next obvious step is to change the above code again, this time verifying the validation result with the ValidationResult function:

package main

import (
    "net/http"

    gv "github.com/bube054/ginvalidator"
    vgo "github.com/bube054/validatorgo"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/hello",
        gv.NewQuery("person", nil).
            Chain().
            Not().
            Empty(&vgo.IsEmptyOpts{IgnoreWhitespace: false}).
            Validate(),
        func(ctx *gin.Context) {
            result, err := gv.ValidationResult(ctx)
            if err != nil {
                ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
                    "message": "The server encountered an unexpected error.",
                })
                return
            }

            if len(result) != 0 {
                ctx.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{
                    "errors": result,
                })
                return
            }

            person := ctx.Query("person")
            ctx.String(http.StatusOK, "Hello, %s!", person)
        })

    r.Run()
}

Now, if you access http://localhost:8080/hello again, you’ll see the following JSON content, formatted for clarity:

{
  "errors": [
    {
      "location": "queries",
      "message": "Invalid value",
      "field": "person",
      "value": ""
    }
  ]
}

Now, what this is telling us is that

  • there's been exactly one error in this request;
  • this field is called person;
  • it's located in the query string (location: "queries");
  • the error message that was given was "Invalid value".

This is a better scenario, but it can still be improved. Let's continue.

Creating better error messages

All request location validators accept an optional second argument, which is a function used to format the error message. If nil is provided, a default, generic error message will be used, as shown in the example above.

package main

import (
    "net/http"

    gv "github.com/bube054/ginvalidator"
    vgo "github.com/bube054/validatorgo"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/hello",
        gv.NewQuery("person",
            func(initialValue, sanitizedValue, validatorName string) string {
                return "Please enter your name."
            },
        ).Chain().
            Not().
            Empty(&vgo.IsEmptyOpts{IgnoreWhitespace: false}).
            Validate(),
        func(ctx *gin.Context) {
            result, err := gv.ValidationResult(ctx)
            if err != nil {
                ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
                    "message": "The server encountered an unexpected error.",
                })
                return
            }

            if len(result) != 0 {
                ctx.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{
                    "errors": result,
                })
                return
            }

            person := ctx.Query("person")
            ctx.String(http.StatusOK, "Hello, %s!", person)
        })

    r.Run()
}

Now if you access http://localhost:8080/hello again, what you'll see is the following JSON content, with the new error message:

{
  "errors": [
    {
      "location": "queries",
      "message": "Please enter your name.",
      "field": "person",
      "value": ""
    }
  ]
}
Accessing validated/sanitized data

You can use GetMatchedData, which automatically collects all data that ginvalidator has validated and/or sanitized. This data can then be accessed using the Get method of MatchedData:

package main

import (
    "fmt"
    "net/http"

    gv "github.com/bube054/ginvalidator"
    vgo "github.com/bube054/validatorgo"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET(
        "/hello",
        gv.NewQuery(
            "person",
            func(initialValue, sanitizedValue, validatorName string) string {
                return "Please enter your name."
            },
        ).Chain().
            Not().
            Empty(&vgo.IsEmptyOpts{IgnoreWhitespace: false}).
            Validate(),
        func(ctx *gin.Context) {
            result, err := gv.ValidationResult(ctx)
            if err != nil {
                ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
                    "message": "The server encountered an unexpected error.",
                })
                return
            }

            if len(result) != 0 {
                ctx.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{
                    "errors": result,
                })
                return
            }

            data, err := gv.GetMatchedData(ctx)
            if err != nil {
                ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
                    "message": "The server encountered an unexpected error.",
                })
                return
            }

            person, ok := data.Get(gv.QueryLocation, "person")
            if !ok {
                ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
                    "message": fmt.Sprintf(
                        "The server could not find 'person' in the expected location: %s. Also please ensure you're using the correct location, such as Body, Header, Cookie, Query, or Param.",
                        gv.QueryLocation,
                    ),
                })
                return
            }

            ctx.String(http.StatusOK, "Hello, %s!", person)
        },
    )

    r.Run()
}

open http://localhost:8080/hello?person=John to salute John!

Available Data Locations 🚩

The following are the valid data locations you can use:

  • BodyLocation: Represents the request body.
  • CookieLocation: Represents cookies in the request.
  • QueryLocation: Represents query parameters in the URL.
  • ParamLocation: Represents path parameters in the request.
  • HeaderLocation: Represents the headers in the request.

Each of these locations includes a String method that returns the location where validated/sanitized data is stored.

Sanitizing inputs

While the user can no longer send empty person names, it can still inject HTML into your page! This is known as the Cross-Site Scripting vulnerability (XSS). Let's see how it works. Go to http://localhost:8080/hello?person=<b>John</b>, and you should see "Hello, John!". While this example is fine, an attacker could change the person query string to a <script> tag which loads its own JavaScript that could be harmful. In this scenario, one way to mitigate the issue with ginvalidator is to use a sanitizer, most specifically Escape, which transforms special HTML characters with others that can be represented as text.

package main

import (
    "fmt"
    "net/http"

    gv "github.com/bube054/ginvalidator"
    vgo "github.com/bube054/validatorgo"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/hello",
        gv.NewQuery("person",
            func(initialValue, sanitizedValue, validatorName string) string {
                return "Please enter your name."
            },
        ).Chain().
            Not().
            Empty(&vgo.IsEmptyOpts{IgnoreWhitespace: false}).
            Escape(). // Added sanitizer
            Validate(),
        func(ctx *gin.Context) {
            result, err := gv.ValidationResult(ctx)
            if err != nil {
                ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
                    "message": "The server encountered an unexpected error.",
                })
                return
            }

            if len(result) != 0 {
                ctx.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{
                    "errors": result,
                })
                return
            }

            data, err := gv.GetMatchedData(ctx)
            if err != nil {
                ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
                    "message": "The server encountered an unexpected error.",
                })
                return
            }

            person, ok := data.Get(gv.QueryLocation, "person")
            if !ok {
                ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
                    "message": fmt.Sprintf(
                        "The server could not find 'person' in the expected location: %s. Also please ensure you're using the correct location, such as Body, Header, Cookie, Query, or Param.",
                        gv.QueryLocation,
                    ),
                })
                return
            }

            ctx.String(http.StatusOK, "Hello, %s!", person)
        })

    r.Run()
}

Now, if you restart the server and refresh the page, what you'll see is "Hello, &lt;b&gt;John&lt;b&gt;!". Our example page is no longer vulnerable to XSS!

⚠️ Caution:
ginvalidator does not modify http.Request values during sanitization. To access sanitized data, always use the GetMatchedData function.

The Validation Chain

The validation chain is one of the main concepts in ginvalidator, therefore it's useful to learn about it, so that you can use it effectively.

But don't worry: if you've read through the Getting Started guide, you have already used validation chains without even noticing!

What are validation chains?

Validation chains are created using the following functions, each targeting a specific location in the HTTP request:

  • NewBody: Validates data from the http.Request body. Its location is BodyLocation.
  • NewCookie: Validates data from the http.Request cookies. Its location is CookieLocation.
  • NewHeader: Validates data from the http.Request headers. Its location is HeaderLocation.
  • NewParam: Validates data from the Gin route parameters. Its location is ParamLocation.
  • NewQuery: Validates data from the http.Request query parameters. Its location is QueryLocation.

They have this name because they wrap the value of a field with validations (or sanitizations), and each of its methods returns itself. This pattern is usually called method chaining, hence why the name validation chain.

Validation chains not only have a number of useful methods for defining validations, sanitizations and modifications but they also have methods Validate which returns the Gin middleware handler function.

This is an example of how validation chains are usually used, and how you can read one:

  r.Get(
    "newsletter",
    // For the `email` field in ctx.GetRawData()...
    gv.NewBody("email", nil)
    // the actual validation chain
    .Chain()
    // ...mark the field as optional
    .Optional()
    // ...and when it's present, trim its value, then validate it as an email address
    .Trim("")
    .Email(nil),
    maybeSubscribeToNewsletter,
  )
Features

A validation chain has three kinds of methods: validators, sanitizers and modifiers.

Validators determine if the value of a request field is valid. This means checking if the field is in the format that you expect it to be. For example, if you're building a sign up form, your requirements could be that the username must be an e-mail address, and that passwords must be at least 8 characters long.

If the value is invalid, an error is recorded for that field using some error message. This validation error can then be retrieved at a later point in the Gin route handler and returned to the user.

They are:

Sanitizers transform the field value. They are useful to remove noise from the value and perhaps even to provide some basic line of defense against threats.

Sanitizers persist the updated fields value back into the Gin Contexts, so that it's usable by other ginvalidator functions, your own route handler code, and even other middlewares.

They are:

Modifiers define how validation chains behave when they are run.

They are:

📝 Note:
These methods are thoroughly documented using GoDoc within the pkg.go.dev ginvalidator documentation. If any details are unclear, you may also want to refer to related functions within the validatorgo package for additional context, which I’ll be explaining below.

Standard validators/sanitizers

All of the functionality exposed by the validation chain actually comes from validatorgo, one of my other open source go packages which specializes in string validation/sanitation. Please check it out, star and share 🙏🙏🙏, Thank You.

This includes all of validatorgo validators and sanitizers, from commonly used IsEmail, IsLength, and Trim to the more niche IsISBN, IsMultibyte and StripLow!

These are called standard validators and standard sanitizers in ginvalidator. But without the Is prefix from validatorgo.

Chaining order

The order in which you call methods on a validation chain usually matters. They are almost always run in the order that they are specified, therefore you can tell what a validation chain will do just by reading its definition, from first chained method to last.

Take the following snippet as an example:

// Validate if search_query is not empty, then trim it
NewQuery("search_query", nil).Chain().Not().Empty().Trim("").Validate();

In this case, if the user passes a "search_query" value that is composed of whitespaces only, it won't be empty, therefore the validation passes. But since the .Trim() sanitizer is there, the whitespace's will be removed, and the field will become empty, so you actually end up with a false positive.

Now, compare it with the below snippet:

// Trim search_query, then validate if it's not empty
NewQuery("search_query", nil).Chain().Trim("").Not().Empty().Validate();

This chain will more sensibly remove whitespace's, and then validate if the value is not empty.

One exception to this rule is .Optional(): It can be placed at any point in the chain and it will mark the chain as optional.

Reusing validation chains

If you wish to reuse the same chain, it's a good idea to return them from functions:

func createEmailValidator() gin.HandlerFunc {
  return gv.NewBody("email", nil).Chain().Email(nil).Validate()
}

func handleLoginRoute(ctx *gin.Context) {
  // Handle login route
}

func handleSignupRoute(ctx *gin.Context) {
  // Handle signup route
}

r.POST("/login", createEmailValidator(), handleLoginRoute)
r.POST("/signup", createEmailValidator(), handleSignupRoute)

Field Selection

In ginvalidator, a field is any value that is either validated or sanitized and it is string.

Pretty much every function or value returned by ginvalidator reference fields in some way. For this reason, it's important to understand the field path syntax both for when selecting fields for validation, and when accessing the validation errors or validated data.

Syntax
  • Body fields are only valid for the following Content-Types:

    application/json: This uses GJSON path syntax for extracting values. Please refer to the linked documentation for details.

    • Example:
      {
        "user": {
          "name": "John",
          "email": "john.doe@example.com"
        }
      }
      
      With path user.name, the extracted value would be "John".

    application/x-www-form-urlencoded: Typically used for HTML form submissions. Fields are submitted as key-value pairs in the body.

    • Example:
      Content-Type: application/x-www-form-urlencoded
      
      Body:
      name=John&email=john.doe@example.com
      
      Field "name" would have the value "John", and "email" would have the value "john.doe@example.com".

    multipart/form-data: Commonly used for file uploads or when submitting form data with files.

    • Example:

      Content-Type: multipart/form-data
      

      Body:

      --boundary
      Content-Disposition: form-data; name="name"
      
      John
      --boundary
      Content-Disposition: form-data; name="file"; filename="resume.pdf"
      Content-Type: application/pdf
      
      [binary data]
      --boundary--
      

      Field "name" would have the value "John", and "file" would be the uploaded file.

  • Query fields correspond to URL search parameters, and their values are automatically url unescaped by Gin.
    Examples:

    • Field: "name", Value: "John"
      /hello?name=John
      
    • Field: "full_name", Value: "John Doe"
      /hello?full_name=John%20Doe
      
  • Param fields represent URL path parameters, and their values are automatically unescaped by ginvalidator.
    Example:

    • Field: "id", Value: "123"
      /users/:id
      
  • Header fields are HTTP request headers, and their values are not unescaped. A log warning will appear if you provide a non-canonical header key.
    Example:

    • Field: "User-Agent", Value: "Mozilla/5.0"
      Header: "User-Agent", Value: "Mozilla/5.0"
      
  • Cookies fields are HTTP cookies, and their values are automatically url unescaped by Gin.
    Example:

    • Field: "session_id", Value: "abc 123"
      Cookie: "session_id=abc%20123"
      

Customizing express-validator

If the server you're building is anything but a very simple one, you'll need validators, sanitizers and error messages beyond the ones built into ginvalidator sooner or later.

Custom Validators and Sanitizers

A classic need that ginvalidator can't fulfill for you, and that you might run into, is validating whether an e-mail address is in use or not when a user signing up.

It's possible to do this in ginvalidator by implementing a custom validator.

A CustomValidator is a method available on the validation chain, that receives a special function CustomValidatorFunc, and have to returns a boolean that will determine if the field is valid or not.

A CustomSanitizer is also a method available on the validation chain, that receives a special function CustomSanitizerFunc, and have to returns the new sanitized value.

Implementing a custom validator

A CustomValidator can be asynchronous by using goroutines and a sync.WaitGroup to handle concurrent operations. Within the validator, you can spin up goroutines for each asynchronous task, adding each task to the WaitGroup. Once all tasks complete, the validator should return a boolean.

For example, in order to check that an e-mail is not in use:

func isUserPresent(email string) bool {
    return email == "existing@example.com"
}

r.POST("/create-user",
    gv.
      NewBody("email", nil).
      Chain().
      CustomValidator(
        func(r *http.Request, initialValue, sanitizedValue string) bool {
          var exists bool
          var wg sync.WaitGroup
          wg.Add(1)

          go func() {
            defer wg.Done()
            exists = isUserPresent(sanitizedValue)
          }()

          wg.Wait()

          return !exists
        },
      ).
      Validate(),

    func(ctx *gin.Context) {
      // Handle the request
    },
)

Or maybe you could also verify that the password matches the repeat:

type createUser struct {
  Password             string `json:"password"`
  PasswordConfirmation string `json:"passwordConfirmation"`
}

r.POST("/create-user",
    gv.NewBody("password", nil).
    Chain().
    Matches(regexp.MustCompile(`^[A-Za-z\d]{8,}$`)).
    Validate(),
  gv.NewBody("passwordConfirmation", nil).
    Chain().
    CustomValidator(func(r *http.Request, initialValue, sanitizedValue string) bool {
      data, err := io.ReadAll(req.Body)
      if err != nil {
      return false
      }

      // Refill the request body to allow further reads, if needed.
      req.Body = io.NopCloser(bytes.NewBuffer(data))

      var user createUser
      json.Unmarshal(data, &user)

      return sanitizedValue == user.PasswordConfirmation
    }).
    Validate(),
  func(ctx *gin.Context) {
    // Handle request
  },
)

⚠️ Caution: If the request body will be accessed multiple times—whether in the same validation chain, in another validation chain for the same request context, or in subsequent handlers—ensure you reset the request body after each read. Failing to do so can lead to errors or missing data when the body is read again.

Implementing a custom sanitizer

CustomSanitizer don't have many rules. Whatever the value that they return, is the new value that the field will acquire. Custom sanitizers can also be asynchronous by using goroutines and a sync.WaitGroup to handle concurrent operations.

r.POST("/user/:id",
    gv.NewParam("id", nil).
      Chain().
      CustomSanitizer(
        func(r *http.Request, initialValue, sanitizedValue string) string {
          return strings.Repeat(sanitizedValue, 3) // some string manipulation
        },
      ).
      Validate(),

    func(ctx *gin.Context) {
      // Handle request
    },
)
Error Messages

Whenever a field value is invalid, an error message is recorded for it. The default error message is "Invalid value", which is not descriptive at all of what the error is, so you might need to customize it. You can customize by

gv.NewBody("email",
    func(initialValue, sanitizedValue, validatorName string) string {
        switch validatorName {
        case gv.EmailValidatorName:
            return "Email is not valid."
        case gv.EmptyValidatorName:
            return "Email is empty."
        default:
            return gv.DefaultValChainErrMsg
        }
    },
).
Chain().
Not().Empty(nil).
Email(nil).
Validate()
  • initialValue is the original value extracted from the request (before any sanitization).
  • sanitizedValue is the value after it has been sanitized (if applicable).
  • validatorName is the name of the validator that failed, which helps identify the validation rule that did not pass.

For a complete list of validator names, refer to the ginvalidator constants.

Maintainers
  • bube054 - Attah Gbubemi David (author)

License

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

Documentation

Overview

Package ginvalidator is a set of Gin middlewares that wraps the extensive collection of validators and sanitizers offered by validatorgo.

It allows you to combine them in many ways so that you can validate and sanitize your express requests, and offers tools to determine if the request is valid or not, which data was matched according to your validators, and so on.

It is based on the popular js/express library express-validator

Index

Constants

View Source
const (
	BailModifierFuncName     string = "Bail"
	IfModifierFuncName       string = "If"
	NotModifierFuncName      string = "Not"
	SkipModifierFuncName     string = "Skip"
	OptionalModifierFuncName string = "Optional"
)
View Source
const (
	CustomSanitizerFuncName         string = "CustomSanitizer"
	BlacklistSanitizerFuncName      string = "Blacklist"
	EscapeSanitizerFuncName         string = "Escape"
	LTrimSanitizerFuncName          string = "LTrim"
	NormalizeEmailSanitizerFuncName string = "NormalizeEmail"
	RTrimSanitizerFuncName          string = "RTrim"
	StripLowSanitizerFuncName       string = "StripLow"
	ToBooleanSanitizerFuncName      string = "ToBoolean"
	ToDateSanitizerFuncName         string = "ToDate"
	ToFloatSanitizerFuncName        string = "ToFloat"
	ToIntSanitizerFuncName          string = "ToInt"
	TrimSanitizerFuncName           string = "Trim"
	UnescapeSanitizerFuncName       string = "Unescape"
	WhitelistSanitizerFuncName      string = "Whitelist"
)
View Source
const (
	CustomValidatorName             string = "CustomValidator"
	ContainsValidatorName           string = "Contains"
	EqualsValidatorName             string = "Equals"
	AbaRoutingValidatorName         string = "AbaRouting"
	AfterValidatorName              string = "After"
	AlphaValidatorName              string = "Alpha"
	AlphanumericValidatorName       string = "Alphanumeric"
	ArrayValidatorName              string = "Array"
	AsciiValidatorName              string = "Ascii"
	BTCAddressValidatorName         string = "BTCAddress"
	Base32ValidatorName             string = "Base32"
	Base58ValidatorName             string = "Base58"
	Base64ValidatorName             string = "Base64"
	BeforeValidatorName             string = "Before"
	BicValidatorName                string = "Bic"
	BooleanValidatorName            string = "Boolean"
	ByteLengthValidatorName         string = "ByteLength"
	CountryCodeValidatorName        string = "CountryCode"
	CreditCardValidatorName         string = "CreditCard"
	CurrencyValidatorName           string = "Currency"
	DataURIValidatorName            string = "DataURI"
	DateValidatorName               string = "Date"
	DecimalValidatorName            string = "Decimal"
	DivisibleByValidatorName        string = "DivisibleBy"
	EANValidatorName                string = "EAN"
	EmailValidatorName              string = "Email"
	EmptyValidatorName              string = "Empty"
	EthereumAddressValidatorName    string = "EthereumAddress"
	FQDNValidatorName               string = "FQDN"
	FloatValidatorName              string = "Float"
	FreightContainerIDValidatorName string = "FreightContainerID"
	FullWidthValidatorName          string = "FullWidth"
	HSLValidatorName                string = "HSL"
	HalfWidthValidatorName          string = "HalfWidth"
	HashValidatorName               string = "Hash"
	HexColorValidatorName           string = "HexColor"
	HexadecimalValidatorName        string = "Hexadecimal"
	IBANValidatorName               string = "IBAN"
	IMEIValidatorName               string = "IMEI"
	IPValidatorName                 string = "IP"
	IPRangeValidatorName            string = "IPRange"
	ISBNValidatorName               string = "ISBN"
	ISINValidatorName               string = "ISIN"
	ISO31661Alpha2ValidatorName     string = "ISO31661Alpha2"
	ISO31661Alpha3ValidatorName     string = "ISO31661Alpha3"
	ISO31661NumericValidatorName    string = "ISO31661Numeric"
	ISO6346ValidatorName            string = "ISO6346"
	ISO6391ValidatorName            string = "ISO6391"
	ISO8601ValidatorName            string = "ISO8601"
	ISRCValidatorName               string = "ISRC"
	ISSNValidatorName               string = "ISSN"
	IdentityCardValidatorName       string = "IdentityCard"
	InValidatorName                 string = "In"
	IntValidatorName                string = "Int"
	ISO4217ValidatorName            string = "ISO4217"
	JSONValidatorName               string = "JSON"
	JWTValidatorName                string = "JWT"
	LatLongValidatorName            string = "LatLong"
	LengthValidatorName             string = "Length"
	LicensePlateValidatorName       string = "LicensePlate"
	LocaleValidatorName             string = "Locale"
	LowerCaseValidatorName          string = "LowerCase"
	LuhnNumberValidatorName         string = "LuhnNumber"
	MD5ValidatorName                string = "MD5"
	MacAddressValidatorName         string = "MacAddress"
	MagnetURIValidatorName          string = "MagnetURI"
	MailtoURIValidatorName          string = "MailtoURI"
	MimeTypeValidatorName           string = "MimeType"
	MobilePhoneValidatorName        string = "MobilePhone"
	MongoIDValidatorName            string = "MongoID"
	MultibyteValidatorName          string = "Multibyte"
	NumericValidatorName            string = "Numeric"
	OctalValidatorName              string = "Octal"
	ObjectValidatorName             string = "Object"
	PassportNumberValidatorName     string = "PassportNumber"
	PortValidatorName               string = "Port"
	PostalCodeValidatorName         string = "PostalCode"
	RFC3339ValidatorName            string = "RFC3339"
	RgbColorValidatorName           string = "RgbColor"
	SemVerValidatorName             string = "SemVer"
	SlugValidatorName               string = "Slug"
	StrongPasswordValidatorName     string = "StrongPassword"
	SurrogatePairValidatorName      string = "SurrogatePair"
	TaxIDValidatorName              string = "TaxID"
	TimeValidatorName               string = "Time"
	ULIDValidatorName               string = "ULID"
	URLValidatorName                string = "URL"
	UUIDValidatorName               string = "UUID"
	UpperCaseValidatorName          string = "UpperCase"
	VATValidatorName                string = "VAT"
	VariableWidthValidatorName      string = "VariableWidth"
	WhitelistedValidatorName        string = "Whitelisted"
	MatchesValidatorName            string = "Matches"
)
View Source
const DefaultValChainErrMsg string = "Invalid value"
View Source
const GinValidatorCtxErrorsStoreName string = "__ginvalidator__ctx__errors__"

GinValidatorCtxErrorsStoreName is the key, where the validation errors are stored.

View Source
const GinValidatorCtxMatchedDataStoreName string = "__ginvalidator__matched__data__"

Variables

View Source
var (
	// ErrNilCtxMatchedData is returned when a nil context is passed, preventing extraction of matched data.
	ErrNilCtxMatchedData = errors.New("nil context provided: unable to extract matched data")

	// ErrNoMatchedData is returned when no matched data is found in the context.
	ErrNoMatchedData = errors.New("no matched data available in context")
)
View Source
var (
	// ErrFieldExtractionFromNilCtx occurs when an operation attempts to extract a field from a nil Gin context.
	ErrFieldExtractionFromNilCtx = errors.New("failed to extract field: gin context is nil")

	// ErrExtractionInvalidContentType occurs when the request contains an unsupported or missing Content-Type header.
	ErrExtractionInvalidContentType = errors.New("failed to extract field: unsupported or missing Content-Type header")

	// ErrExtractionInvalidJSON occurs when JSON parsing fails due to malformed JSON in the request body.
	ErrExtractionInvalidJSON = errors.New("failed to extract field: invalid JSON in request body")
)
View Source
var (
	// ErrNilCtxValidationResult is returned when a nil context is provided, making it impossible to extract validation results.
	ErrNilCtxValidationResult = errors.New("nil context provided: unable to extract validation result")

	// ErrNoValidationResult is returned when no validation result is found in the context.
	ErrNoValidationResult = errors.New("validation result not found in context")
)

Functions

func NewValidationChainRule

func NewValidationChainRule(opts ...func(*validationChainRule)) validationChainRule

NewValidationChainRule creates a new validationChainRule with the specified options.

func SortValidationErrors

func SortValidationErrors(errors []ValidationChainError)

Types

type Body

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

Body is used to validate data from the `http.Request` body.

func NewBody

func NewBody(field string, errFmtFunc ErrFmtFuncHandler) Body

NewBody constructs a Body validator for the given field. Returns a Body object that can be used to create validation chains.

Parameters:

  • field: the name of the field to validate. It uses gjson for its json field extraction syntax.
  • errFmtFunc: a handler for formatting error messages.

func (Body) Chain

func (b Body) Chain() ValidationChain

Chain initializes a validation chain for the given body field. It creates a new ValidationChain object that will validate the specified field and format error messages using the provided ErrFmtFuncHandler.

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

Cookie is used to validate data from the `http.Request` cookies.

func NewCookie

func NewCookie(field string, errFmtFunc ErrFmtFuncHandler) Cookie

NewCookie constructs a Cookie validator for the given field. Returns a Cookie object that can be used to create validation chains.

Parameters:

  • field: the name of the field to validate.
  • errFmtFunc: a handler for formatting error messages.

func (Cookie) Chain

func (c Cookie) Chain() ValidationChain

Chain initializes a validation chain for the given body field. It creates a new ValidationChain object that will validate the specified field and format error messages using the provided ErrFmtFuncHandler.

type CustomSanitizerFunc

type CustomSanitizerFunc func(r *http.Request, initialValue, sanitizedValue string) string

CustomSanitizerFunc defines a function that computes and returns the new sanitized value.

Parameters:

  • req: The HTTP request context derived from `http.Request`.
  • initialValue: The original value derived from the specified field.
  • sanitizedValue: The current sanitized value after applying previous sanitizers.

type CustomValidatorFunc

type CustomValidatorFunc func(r *http.Request, initialValue, sanitizedValue string) bool

CustomValidatorFunc defines a function that evaluates whether the value is valid according to your custom logic.

Parameters:

  • r: The HTTP request context derived from `http.Request`.
  • initialValue: The original value derived from the specified field.
  • sanitizedValue: The current sanitized value after applying previous sanitizers.

type ErrFmtFuncHandler

type ErrFmtFuncHandler func(initialValue, sanitizedValue, validatorName string) string

ErrFmtFuncHandler is a function type used to format validation error messages. It takes in the initial and sanitized values of a field, along with the name of the validator that triggered the error, and returns a formatted error message as a string.

Parameters:

  • initialValue: The original value of the field before sanitization.
  • sanitizedValue: The value of the field after applying sanitization or validation.
  • validatorName: The name of the validator that was applied and caused the error.

Returns:

  • A string representing the formatted error message based on the provided values and validator.
type Header struct {
	// contains filtered or unexported fields
}

Header is used to validate data from the `http.Request` headers.

func NewHeader

func NewHeader(field string, errFmtFunc ErrFmtFuncHandler) Header

NewHeader constructs a Header validator for the given field. Returns a Header object that can be used to create validation chains.

Parameters:

  • field: the name of the field to validate.
  • errFmtFunc: a handler for formatting error messages.

func (Header) Chain

func (h Header) Chain() ValidationChain

Chain initializes a validation chain for the given body field. It creates a new ValidationChain object that will validate the specified field and format error messages using the provided ErrFmtFuncHandler.

type IfModifierFunc

type IfModifierFunc func(r *http.Request, initialValue, sanitizedValue string) bool

IfModifierFunc defines a function that determines whether the validation chain should stop or continue. It returns `true` if the chain should stop, or `false` if it should continue.

Parameters:

  • req: the HTTP request context derived from `http.Request`.
  • initialValue: the original value derived from the specified field.
  • sanitizedValue: the current sanitized value after applying previous sanitizers.

type MatchedData

type MatchedData map[string]MatchedDataFieldValues

MatchedData is a map of request locations and fields. The keys in MatchedData represent the request locations where fields can be found. Possible locations include:

  • "body": Data from the request body.
  • "cookies": Data from request cookies.
  • "headers": Data from request headers.
  • "params": Data from URL parameters.
  • "queries": Data from URL query parameters.

func GetMatchedData

func GetMatchedData(ctx *gin.Context) (MatchedData, error)

GetMatchedData extracts and returns matched data from various locations in the request context. It retrieves fields and values from predefined request locations such as query parameters, body, URL parameters, and headers.

Parameters:

  • ctx: The Gin context, which provides access to the HTTP request and response.

Returns:

  • MatchedData: A map containing fields and their values organized by request location.
  • error: An error if there was an issue extracting data from the context; otherwise, nil.

func (MatchedData) Get added in v0.2.0

func (md MatchedData) Get(loc RequestLocation, field string) (string, bool)

Get retrieves a specific field's value from a given request location within MatchedData. Parameters:

  • loc: The request location to search in (e.g., "body", "cookies", "headers", "params", "queries").
  • field: The name of the field to retrieve.

Returns:

  • The value associated with the specified field at the given location (as a string).
  • A boolean indicating if the field exists (true if found, false if not).

type MatchedDataFieldValues

type MatchedDataFieldValues map[string]string

MatchedDataFieldValues is a map of fields and their values for a request location.

type Param

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

Param is used to validate data from the gins route parameters.

func NewParam

func NewParam(field string, errFmtFunc ErrFmtFuncHandler) Param

NewParam constructs a Param validator for the given field. Returns a Param object that can be used to create validation chains.

Parameters:

  • field: the name of the field to validate.
  • errFmtFunc: a handler for formatting error messages.

func (Param) Chain

func (p Param) Chain() ValidationChain

Chain initializes a validation chain for the given body field. It creates a new ValidationChain object that will validate the specified field and format error messages using the provided ErrFmtFuncHandler.

type Query

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

Query is used to validate data from the `http.Request` queries.

func NewQuery

func NewQuery(field string, errFmtFunc ErrFmtFuncHandler) Query

NewQuery constructs a Query validator for the given field. Returns a Query object that can be used to create validation chains.

Parameters:

  • field: the name of the field to validate.
  • errFmtFunc: a handler for formatting error messages.

func (Query) Chain

func (q Query) Chain() ValidationChain

Chain initializes a validation chain for the given body field. It creates a new ValidationChain object that will validate the specified field and format error messages using the provided ErrFmtFuncHandler.

type RequestLocation

type RequestLocation int

RequestLocation defines different locations where data can be extracted from the request.

const (
	// BodyLocation represents the request body.
	BodyLocation RequestLocation = iota

	// CookieLocation represents cookies in the request.
	CookieLocation

	// HeaderLocation represents the headers in the request.
	HeaderLocation

	// ParamLocation represents path parameters in the request.
	ParamLocation

	// QueryLocation represents query parameters in the URL of the request.
	QueryLocation
)

Constants representing different locations in a request.

func (RequestLocation) String

func (l RequestLocation) String() string

String returns a string representation of the RequestLocation.

type SkipModifierFunc

type SkipModifierFunc func(r *http.Request, initialValue, sanitizedValue string) bool

SkipModifierFunc defines a function that determines wwhether the next validator, modifier or sanitizer in validation chain should be skipped. It returns `true` if the next chain should skipped, or `false` if it should continue.

Parameters:

  • req: the HTTP request context derived from `http.Request`.
  • initialValue: the original value derived from the specified field.
  • sanitizedValue: the current sanitized value after applying previous sanitizers.

type ValidationChain

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

func NewValidationChain

func NewValidationChain(field string, errFmtFunc ErrFmtFuncHandler, reqLoc RequestLocation) ValidationChain

func (ValidationChain) AbaRouting

func (v ValidationChain) AbaRouting() ValidationChain

AbaRouting is a validator that checks if the string is an ABA routing number for US bank account / cheque.

This function uses the IsAbaRouting from validatorgo package to perform the validation logic.

func (ValidationChain) After

func (v ValidationChain) After(opts *vgo.IsAfterOpts) ValidationChain

After is a validator that checks if the string is a date that is after the specified date.

This function uses the IsAfter from validatorgo package to perform the validation logic.

func (ValidationChain) Alpha

func (v ValidationChain) Alpha(opts *vgo.IsAlphaOpts) ValidationChain

Alpha is a validator that checks if the string contains only letters (a-zA-Z).

This function uses the IsAlpha from validatorgo package to perform the validation logic.

func (ValidationChain) Alphanumeric

func (v ValidationChain) Alphanumeric(opts *vgo.IsAlphanumericOpts) ValidationChain

Alphanumeric is a validator that checks if the string contains only letters and numbers (a-zA-Z0-9).

This function uses the IsAlphanumeric from validatorgo package to perform the validation logic.

func (ValidationChain) Array added in v0.3.1

func (v ValidationChain) Array(opts *vgo.IsArrayOpts) ValidationChain

Base32 is a validator to check that a value is an array.

This function uses the IsArray from validatorgo package to perform the validation logic.

func (ValidationChain) Ascii

func (v ValidationChain) Ascii() ValidationChain

Ascii is a validator that checks if the string contains ASCII chars only.

This function uses the IsAscii from validatorgo package to perform the validation logic.

func (ValidationChain) BTCAddress

func (v ValidationChain) BTCAddress() ValidationChain

BTCAddress is a validator that checks if the string is a valid BTC address.

This function uses the IsBTCAddress from validatorgo package to perform the validation logic.

func (ValidationChain) Bail

func (m ValidationChain) Bail() ValidationChain

Bail is a modifier that stops running the validation chain if any of the previous validators failed.

This is useful to prevent a custom validator that touches a database or external API from running when you know it will fail.

.Bail() can be used multiple times in the same validation chain if desired.

func (ValidationChain) Base32

func (v ValidationChain) Base32(opts *vgo.IsBase32Opts) ValidationChain

Base32 is a validator that checks if the string is base32 encoded.

This function uses the IsBase32 from validatorgo package to perform the validation logic.

func (ValidationChain) Base58

func (v ValidationChain) Base58() ValidationChain

Base58 is a validator that checks if the string is base32 encoded.

This function uses the IsBase58 from validatorgo package to perform the validation logic.

func (ValidationChain) Base64

func (v ValidationChain) Base64(opts *vgo.IsBase64Opts) ValidationChain

Base64 is a validator that checks if the string is base64 encoded.

This function uses the IsBase64 from validatorgo package to perform the validation logic.

func (ValidationChain) Before

func (v ValidationChain) Before(opts *vgo.IsBeforeOpts) ValidationChain

Before is a validator that checks if the string is a date that is before the specified date.

This function uses the IsBefore from validatorgo package to perform the validation logic.

func (ValidationChain) Bic

func (v ValidationChain) Bic() ValidationChain

Bic is a validator that checks if the string is a BIC (Bank Identification Code) or SWIFT code.

This function uses the IsBic from validatorgo package to perform the validation logic.

func (ValidationChain) Blacklist

func (s ValidationChain) Blacklist(blacklistedChars string) ValidationChain

Blacklist is a sanitizer that remove characters that appear in the blacklist.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to Blacklist.

func (ValidationChain) Boolean

func (v ValidationChain) Boolean(opts *vgo.IsBooleanOpts) ValidationChain

Boolean validator that checks if the string is a boolean.

This function uses the IsBoolean from validatorgo package to perform the validation logic.

func (ValidationChain) ByteLength

func (v ValidationChain) ByteLength(opts *vgo.IsByteLengthOpts) ValidationChain

ByteLength is a validator that checks if the string's length (in UTF-8 bytes) falls in a range.

This function uses the IsByteLength from validatorgo package to perform the validation logic.

func (ValidationChain) Contains

func (v ValidationChain) Contains(seed string, opts *vgo.ContainsOpt) ValidationChain

Contains is a validator that checks if the string contains the seed.

This function uses the [Contains] from validatorgo package to perform the validation logic.

func (ValidationChain) CreditCard

func (v ValidationChain) CreditCard(opts *vgo.IsCreditCardOpts) ValidationChain

CreditCard is a validator that checks if the string is a credit card number.

This function uses the IsCreditCard from validatorgo package to perform the validation logic.

func (ValidationChain) Currency

func (v ValidationChain) Currency(opts *vgo.IsCurrencyOpts) ValidationChain

Currency is a validator that checks if the string is a valid currency amount.

This function uses the IsCurrency from validatorgo package to perform the validation logic.

func (ValidationChain) CustomSanitizer

func (s ValidationChain) CustomSanitizer(csf CustomSanitizerFunc) ValidationChain

CustomSanitizer applies a custom sanitizer function to compute the new sanitized value.

Parameters:

func (ValidationChain) CustomValidator

func (v ValidationChain) CustomValidator(cvf CustomValidatorFunc) ValidationChain

CustomValidator applies a custom validator function.

Parameters:

func (ValidationChain) DataURI

func (v ValidationChain) DataURI() ValidationChain

DataURI is a validator that checks if the string is a data uri format.

This function uses the IsDataURI from validatorgo package to perform the validation logic.

func (ValidationChain) Date

func (v ValidationChain) Date(opts *vgo.IsDateOpts) ValidationChain

Date is a validator that checks if the string is a valid date. e.g. 2002-07-15.

This function uses the IsDate from validatorgo package to perform the validation logic.

func (ValidationChain) Decimal

func (v ValidationChain) Decimal(opts *vgo.IsDecimalOpts) ValidationChain

Decimal is a validator that checks if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.

This function uses the IsDecimal from validatorgo package to perform the validation logic.

func (ValidationChain) DivisibleBy

func (v ValidationChain) DivisibleBy(num int) ValidationChain

DivisibleBy is a validator thats checks if the string is a number(integer not a floating point) that is divisible by another(integer not a floating point).

This function uses the IsDivisibleBy from validatorgo package to perform the validation logic.

func (ValidationChain) EAN

func (v ValidationChain) EAN() ValidationChain

EAN is validator that checks if the string is a valid EAN (European Article Number).

This function uses the IsEAN from validatorgo package to perform the validation logic.

func (ValidationChain) Email

func (v ValidationChain) Email(opts *vgo.IsEmailOpts) ValidationChain

Email is a validator that checks if the string is an email.

This function uses the IsEmail from validatorgo package to perform the validation logic.

func (ValidationChain) Empty

func (v ValidationChain) Empty(opts *vgo.IsEmptyOpts) ValidationChain

Empty is a validator that checks if the string is an email.

This function uses the IsEmpty from validatorgo package to perform the validation logic.

func (ValidationChain) Equals

func (v ValidationChain) Equals(comparison string) ValidationChain

Equals is a validator that checks if the string contains the seed.

This function uses the [Equals] from validatorgo package to perform the validation logic.

func (ValidationChain) Escape

func (s ValidationChain) Escape() ValidationChain

Escape is a sanitizer that replaces <, >, &, ' and ". with HTML entities.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to Escape.

func (ValidationChain) EthereumAddress

func (v ValidationChain) EthereumAddress() ValidationChain

EthereumAddress is a validator checks if the string is an Ethereum address.

This function uses the IsEthereumAddress from validatorgo package to perform the validation logic.

func (ValidationChain) FQDN

func (v ValidationChain) FQDN(opts *vgo.IsFQDNOpts) ValidationChain

FQDN is a validator that checks if the string is a fully qualified domain name (e.g. domain.com).

This function uses the IsFQDN from validatorgo package to perform the validation logic.

func (ValidationChain) Float

func (v ValidationChain) Float(opts *vgo.IsFloatOpts) ValidationChain

Float is a validator that checks if the string is a float.

This function uses the IsFloat from validatorgo package to perform the validation logic.

func (ValidationChain) FreightContainerID

func (v ValidationChain) FreightContainerID() ValidationChain

FreightContainerID is a validator that checks alias for IsISO6346, check if the string is a valid ISO 6346 shipping container identification.

This function uses the IsFreightContainerID from validatorgo package to perform the validation logic.

func (ValidationChain) FullWidth

func (v ValidationChain) FullWidth() ValidationChain

FullWidth validator that checks if the string contains any full-width chars.

This function uses the IsFullWidth from validatorgo package to perform the validation logic.

func (ValidationChain) HSL

func (v ValidationChain) HSL() ValidationChain

HSL is a validator that checks if the string is an HSL (hue, saturation, lightness, optional alpha) color based on CSS Colors Level 4 specification.

This function uses the IsHSL from validatorgo package to perform the validation logic.

func (ValidationChain) HalfWidth

func (v ValidationChain) HalfWidth() ValidationChain

HalfWidth is a validator that checks if the string contains any half-width chars.

This function uses the IsHalfWidth from validatorgo package to perform the validation logic.

func (ValidationChain) Hash

func (v ValidationChain) Hash(algorithm string) ValidationChain

Hash is a validator that checks if the string is a hash of type algorithm.

This function uses the IsHash from validatorgo package to perform the validation logic.

func (ValidationChain) HexColor

func (v ValidationChain) HexColor() ValidationChain

HexColor is a validator that checks if the string is a hexadecimal color.

This function uses the IsHexColor from validatorgo package to perform the validation logic.

func (ValidationChain) Hexadecimal

func (v ValidationChain) Hexadecimal() ValidationChain

Hexadecimal is a validator that checks if the string is a hexadecimal number.

This function uses the IsHexadecimal from validatorgo package to perform the validation logic.

func (ValidationChain) IBAN

func (v ValidationChain) IBAN(countryCode string) ValidationChain

IBAN is a validator that checks if the string is an IBAN (International Bank Account Number).

This function uses the IsIBAN from validatorgo package to perform the validation logic.

func (ValidationChain) IMEI

func (v ValidationChain) IMEI(opts *vgo.IsIMEIOpts) ValidationChain

IMEI is a validator that checks if the string is a valid IMEI number.

This function uses the IsIMEI from validatorgo package to perform the validation logic.

func (ValidationChain) IP

func (v ValidationChain) IP(version string) ValidationChain

IP is a validator that checks if the string is an IP (version 4 or 6).

This function uses the IsIP from validatorgo package to perform the validation logic.

func (ValidationChain) IPRange

func (v ValidationChain) IPRange(version string) ValidationChain

IPRange is a validator that checks if the string is an IPRange (version 4 or 6).

This function uses the IsIPRange from validatorgo package to perform the validation logic.

func (ValidationChain) ISIN

func (v ValidationChain) ISIN() ValidationChain

ISIN is a validator that checks if the string is an ISIN (stock/security identifier).

This function uses the IsISIN from validatorgo package to perform the validation logic.

func (ValidationChain) ISO31661Alpha2

func (v ValidationChain) ISO31661Alpha2() ValidationChain

ISO31661Alpha2 is a validator that checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code.

This function uses the IsISO31661Alpha2 from validatorgo package to perform the validation logic.

func (ValidationChain) ISO31661Alpha3

func (v ValidationChain) ISO31661Alpha3() ValidationChain

ISO31661Alpha3 is a validator that checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code.

This function uses the IsISO31661Alpha3 from validatorgo package to perform the validation logic.

func (ValidationChain) ISO31661Numeric

func (v ValidationChain) ISO31661Numeric() ValidationChain

ISO31661Numeric is a validator that checks check if the string is a valid ISO 3166-1 numeric officially assigned country code.

This function uses the IsISO31661Numeric from validatorgo package to perform the validation logic.

func (ValidationChain) ISO4217

func (v ValidationChain) ISO4217() ValidationChain

ISO4217 is a validator that checks if the string is a valid ISO 4217 officially assigned.

This function uses the IsISO4217 from validatorgo package to perform the validation logic.

func (ValidationChain) ISO6346

func (v ValidationChain) ISO6346() ValidationChain

ISO6346 is a validator that checks if the string is a valid ISO 6346 shipping container identification.

This function uses the IsISO6346 from validatorgo package to perform the validation logic.

func (ValidationChain) ISO6391

func (v ValidationChain) ISO6391() ValidationChain

ISO6391 is a validator that checks if the string is a valid ISO 639-1 language code.

This function uses the IsISO6391 from validatorgo package to perform the validation logic.

func (ValidationChain) ISO8601

func (v ValidationChain) ISO8601(opts *vgo.IsISO8601Opts) ValidationChain

ISO8601 is a validator that checks if the string is a valid ISO 8601 date.

This function uses the IsISO8601 from validatorgo package to perform the validation logic.

func (ValidationChain) ISRC

func (v ValidationChain) ISRC(allowHyphens bool) ValidationChain

ISRC is a validator that checks if the string is an ISRC.

This function uses the IsISRC from validatorgo package to perform the validation logic.

func (ValidationChain) ISSN

func (v ValidationChain) ISSN(opts *vgo.IsISSNOpts) ValidationChain

ISSN is a validator that checks if the string is an ISSN.

This function uses the IsISSN from validatorgo package to perform the validation logic.

func (ValidationChain) IdentityCard

func (v ValidationChain) IdentityCard(locale string) ValidationChain

IdentityCard is a validator that checks if the string is a valid identity card code.

This function uses the IsIdentityCard from validatorgo package to perform the validation logic.

func (ValidationChain) If

func (m ValidationChain) If(imf IfModifierFunc) ValidationChain

If adds a conditional check to decide whether the validation chain should continue for a field.

The condition is evaluated by the provided IfModifierFunc and the result determines if the validation chain should bail out (`true`) or proceed (`false`).

Parameters:

func (ValidationChain) In

func (v ValidationChain) In(values []string) ValidationChain

In is a validator that checks if the string is in a slice of allowed values.

This function uses the IsIn from validatorgo package to perform the validation logic.

func (ValidationChain) Int

func (v ValidationChain) Int(opts *vgo.IsIntOpts) ValidationChain

Int is a validator that checks if the string is an integer.

This function uses the IsInt from validatorgo package to perform the validation logic.

func (ValidationChain) JSON

func (v ValidationChain) JSON() ValidationChain

JSON is a validator that checks if the string is an JSON.

This function uses the IsJSON from validatorgo package to perform the validation logic.

func (ValidationChain) LTrim

func (s ValidationChain) LTrim(chars string) ValidationChain

LTrim is a sanitizer that trims characters (whitespace by default) from the left-side of the input.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to LTrim.

func (ValidationChain) LatLong

func (v ValidationChain) LatLong(opts *vgo.IsLatLongOpts) ValidationChain

LatLong is a validator that checks if the string is a valid latitude-longitude coordinate.

This function uses the IsLatLong from validatorgo package to perform the validation logic.

func (ValidationChain) Length added in v0.3.1

func (v ValidationChain) Length(opts *vgo.IsLengthOpts) ValidationChain

length is a validator that checks if the string's length falls in a range.

This function uses the IsLength from validatorgo package to perform the validation logic.

func (ValidationChain) LicensePlate

func (v ValidationChain) LicensePlate(locale string) ValidationChain

LicensePlate is a validator that checks if the string matches the format of a country's license plate.

This function uses the IsLicensePlate from validatorgo package to perform the validation logic.

func (ValidationChain) Locale

func (v ValidationChain) Locale() ValidationChain

Locale is a validator that checks if the string is a locale.

This function uses the IsLocale from validatorgo package to perform the validation logic.

func (ValidationChain) LowerCase

func (v ValidationChain) LowerCase() ValidationChain

LowerCase is a validator that checks if the string is lowercase.

This function uses the IsLowerCase from validatorgo package to perform the validation logic.

func (ValidationChain) LuhnNumber

func (v ValidationChain) LuhnNumber() ValidationChain

LuhnNumber is a validator that checks if the string passes the Luhn algorithm check.

This function uses the IsLuhnNumber from validatorgo package to perform the validation logic.

func (ValidationChain) MD5

func (v ValidationChain) MD5() ValidationChain

MD5 is a validator that checks if the string is a MD5 hash.

This function uses the IsMD5 from validatorgo package to perform the validation logic.

func (ValidationChain) MacAddress

func (v ValidationChain) MacAddress(opts *vgo.IsMacAddressOpts) ValidationChain

MacAddress is a validator that checks if the string is a MAC address.

This function uses the IsMacAddress from validatorgo package to perform the validation logic.

func (ValidationChain) MagnetURI

func (v ValidationChain) MagnetURI() ValidationChain

MagnetURI is a validator that checks if the string is a Magnet URI format.

This function uses the IsMagnetURI from validatorgo package to perform the validation logic.

func (ValidationChain) MailtoURI

func (v ValidationChain) MailtoURI(opts *vgo.IsMailToURIOpts) ValidationChain

MailtoURI is a validator that checks if the string is a Mailto URI format.

This function uses the IsMailtoURI from validatorgo package to perform the validation logic.

func (ValidationChain) Matches

func (v ValidationChain) Matches(re *regexp.Regexp) ValidationChain

Matches is a validator that checks if the string matches the regex.

This function uses the IsMatches from validatorgo package to perform the validation logic.

func (ValidationChain) MimeType

func (v ValidationChain) MimeType() ValidationChain

MimeType is a validator that checks if the string matches to a valid MIME type format.

This function uses the IsMimeType from validatorgo package to perform the validation logic.

func (ValidationChain) MobilePhone

func (v ValidationChain) MobilePhone(locales []string, opts *vgo.IsMobilePhoneOpts) ValidationChain

MobilePhone is a validator that checks if the string is a mobile phone number.

This function uses the IsMobilePhone from validatorgo package to perform the validation logic.

func (ValidationChain) MongoID

func (v ValidationChain) MongoID() ValidationChain

MongoID is a validator that checks if the string is a valid hex-encoded representation of a MongoDB ObjectId.

This function uses the IsMongoID from validatorgo package to perform the validation logic.

func (ValidationChain) Multibyte

func (v ValidationChain) Multibyte() ValidationChain

Multibyte is a validator that checks if the string contains one or more multibyte chars.

This function uses the IsMultibyte from validatorgo package to perform the validation logic.

func (ValidationChain) NormalizeEmail

func (s ValidationChain) NormalizeEmail(opts *san.NormalizeEmailOpts) ValidationChain

NormalizeEmail is a sanitizer that canonicalizes an email address. (This doesn't validate that the input is an email, if you want to validate the email use IsEmail beforehand).

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to NormalizeEmail.

func (ValidationChain) Not

func (m ValidationChain) Not() ValidationChain

Not negates the result of the next validator in the chain.

func (ValidationChain) Numeric

func (v ValidationChain) Numeric(opts *vgo.IsNumericOpts) ValidationChain

Numeric is a validator that checks if a string is a number.

This function uses the IsNumeric from validatorgo package to perform the validation logic.

func (ValidationChain) Object added in v0.3.1

func (v ValidationChain) Object(opts *vgo.IsObjectOpts) ValidationChain

Octal is a validator to check that a value is a json object.

This function uses the IsObject from validatorgo package to perform the validation logic.

func (ValidationChain) Octal

func (v ValidationChain) Octal() ValidationChain

Octal is a validator that checks if the string is a valid octal number.

This function uses the IsOctal from validatorgo package to perform the validation logic.

func (ValidationChain) Optional

func (m ValidationChain) Optional() ValidationChain

Optional ignores validation if the value is not present/empty, instead of failing it.

func (ValidationChain) PassportNumber

func (v ValidationChain) PassportNumber(countryCode string) ValidationChain

PassportNumber is a validator that checks if the string is a valid passport number.

This function uses the IsPassportNumber from validatorgo package to perform the validation logic.

func (ValidationChain) Port

func (v ValidationChain) Port() ValidationChain

Port is a validator that checks if the string is a valid port number.

This function uses the IsPort from validatorgo package to perform the validation logic.

func (ValidationChain) PostalCode

func (v ValidationChain) PostalCode(locale string) ValidationChain

PostalCode is a validator that checks if the string is a postal code.

This function uses the IsPostalCode from validatorgo package to perform the validation logic.

func (ValidationChain) RFC3339

func (v ValidationChain) RFC3339() ValidationChain

RFC3339 is a validator that checks if the string is a valid RFC 3339 date.

This function uses the IsRFC3339 from validatorgo package to perform the validation logic.

func (ValidationChain) RTrim

func (s ValidationChain) RTrim(chars string) ValidationChain

RTrim is a sanitizer that trims characters (whitespace by default) from the right-side of the input.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to RTrim.

func (ValidationChain) RgbColor

func (v ValidationChain) RgbColor(opts *vgo.IsRgbOpts) ValidationChain

RgbColor is a validator that checks if the string is a rgb or rgba color.

This function uses the IsRgbColor from validatorgo package to perform the validation logic.

func (ValidationChain) SemVer

func (v ValidationChain) SemVer() ValidationChain

SemVer is a validator that checks if the string is a Semantic Versioning Specification (SemVer).

This function uses the IsSemVer from validatorgo package to perform the validation logic.

func (ValidationChain) Skip

func (m ValidationChain) Skip(smf SkipModifierFunc) ValidationChain

Skip adds a conditional check to decide whether the next validator, modifier or sanitizer in validation chain should be skipped.

The condition is evaluated by the provided SkipModifierFunc and the result determines if the next link in validation chain should be skipped out (`true`) or proceed (`false`).

Parameters:

func (ValidationChain) Slug

func (v ValidationChain) Slug() ValidationChain

Slug is a validator that checks if the string is of type slug.

This function uses the IsSlug from validatorgo package to perform the validation logic.

func (ValidationChain) StripLow

func (s ValidationChain) StripLow(keepNewLines bool) ValidationChain

StripLow is a sanitizer that removes characters with a numerical value < 32 and 127, mostly control characters.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to StripLow.

func (ValidationChain) StrongPassword

func (v ValidationChain) StrongPassword(opts *vgo.IsStrongPasswordOpts) ValidationChain

StrongPassword is a validator that checks if the string is of type strongPassword.

This function uses the IsStrongPassword from validatorgo package to perform the validation logic.

func (ValidationChain) SurrogatePair

func (v ValidationChain) SurrogatePair() ValidationChain

SurrogatePair is a validator that checks if the string contains any surrogate pairs chars.

This function uses the IsSurrogatePair from validatorgo package to perform the validation logic.

func (ValidationChain) TaxID

func (v ValidationChain) TaxID(locale string) ValidationChain

TaxID is a validator that checks if the string is a valid Tax Identification Number.

This function uses the IsTaxID from validatorgo package to perform the validation logic.

func (ValidationChain) Time

func (v ValidationChain) Time(opts *vgo.IsTimeOpts) ValidationChain

Time is a validator that checks if the string is a valid time e.g. 23:01:59

This function uses the IsTime from validatorgo package to perform the validation logic.

func (ValidationChain) ToBoolean

func (s ValidationChain) ToBoolean(strict bool) ValidationChain

ToBoolean is a A sanitizer that converts the input string to a boolean as s string "true" or "false"

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to ToBoolean.

func (ValidationChain) ToDate

func (s ValidationChain) ToDate() ValidationChain

ToDate is a sanitizer that converts the value too a textual representation.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to ToDate.

func (ValidationChain) ToFloat

func (s ValidationChain) ToFloat() ValidationChain

ToFloat is a sanitizer that converts the input string to a float64.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to ToFloat.

func (ValidationChain) ToInt

func (s ValidationChain) ToInt() ValidationChain

ToInt is a sanitizer that converts the input string to an int and also returns an error if the input is not a int. (Beware of octals)

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to ToInt.

func (ValidationChain) Trim

func (s ValidationChain) Trim(chars string) ValidationChain

Trim is a sanitizer that trim characters (whitespace by default) from both sides of the input.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to Trim.

func (ValidationChain) ULID

func (v ValidationChain) ULID() ValidationChain

ULID is a validator that checks if the string is a ULID.

This function uses the IsULID from validatorgo package to perform the validation logic.

func (ValidationChain) URL

func (v ValidationChain) URL(opts *vgo.IsURLOpts) ValidationChain

URL is a validator that checks if the string is URL.

This function uses the IsURL from validatorgo package to perform the validation logic.

func (ValidationChain) UUID

func (v ValidationChain) UUID(version string) ValidationChain

UUID is a validator that checks if the string is an RFC9562 UUID.

This function uses the IsUUID from validatorgo package to perform the validation logic.

func (ValidationChain) Unescape

func (s ValidationChain) Unescape() ValidationChain

Unescape is a A sanitizer that replaces HTML encoded entities with <, >, &, ', ", `, \ and /.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to Unescape.

func (ValidationChain) UpperCase

func (v ValidationChain) UpperCase() ValidationChain

UpperCase is a validator that checks if the string is uppercase.

This function uses the IsUpperCase from validatorgo package to perform the validation logic.

func (ValidationChain) VAT

func (v ValidationChain) VAT(countryCode string) ValidationChain

VAT is a validator that checks if the string is a valid VAT.

This function uses the IsVAT from validatorgo package to perform the validation logic.

func (ValidationChain) Validate

func (v ValidationChain) Validate() gin.HandlerFunc

func (ValidationChain) VariableWidth

func (v ValidationChain) VariableWidth() ValidationChain

VariableWidth is a validator that checks if the string contains a mixture of full and half-width chars.

This function uses the IsVariableWidth from validatorgo package to perform the validation logic.

func (ValidationChain) Whitelist

func (s ValidationChain) Whitelist(whitelistedChars string) ValidationChain

Whitelist is a sanitizer that removes characters that do not appear in the whitelist.

This function uses the validatorgo package to perform the sanitization logic.

Its parameters are according to Whitelist.

func (ValidationChain) Whitelisted

func (v ValidationChain) Whitelisted(chars string) ValidationChain

Whitelisted is a validator that checks if the string consists only of characters that appear in the whitelist chars.

This function uses the IsWhitelisted from validatorgo package to perform the validation logic.

type ValidationChainError

type ValidationChainError struct {
	Location string `json:"location"`
	Msg      string `json:"message"`
	Field    string `json:"field"`
	Value    string `json:"value"`
	// contains filtered or unexported fields
}

ValidationChainError represents an error that occurred during the validation chain for a request. It includes information about the location of the error, the message, the specific field involved, the invalid value. The timestamp (`createdAt`) is used internally to track when the error was created.

Fields:

  • Location: The location in the request where the error occurred (e.g., "body", "cookies", "headers", "params", "queries").
  • Msg: A message describing the validation error.
  • Field: The name of the field that failed validation.
  • Value: The invalid value that triggered the validation error.
  • createdAt: The timestamp when the error was created (used internally for tracking).
  • incId: The autoincrement id (used internally for tracking/sorting).

func NewValidationChainError

func NewValidationChainError(opts ...func(*ValidationChainError)) ValidationChainError

func ValidationResult

func ValidationResult(ctx *gin.Context) ([]ValidationChainError, error)

ValidationResult extracts the validation errors from the Gin context. It retrieves any validation errors that have occurred during the request processing, and returns them as a slice of ValidationChainError structs along with any potential error.

Parameters:

  • ctx: The Gin context, which provides access to the HTTP request and response, including validation error data.

Returns:

  • A slice of ValidationChainError: Contains the details of each validation error encountered, including location, field, and message.
  • error: Returns an error if there is an issue extracting or processing the validation errors; otherwise, nil.

Jump to

Keyboard shortcuts

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