Documentation
¶
Overview ¶
Package validator provides a custom validator middleware for the Fiber web framework. It allows for flexible and extensible validation of incoming request bodies.
Installation ¶
To use this middleware in a Fiber project, Go must be installed and set up.
1. Install the package using Go modules:
go get github.com/H0llyW00dzZ/FiberValidator
2. Import the package in the Fiber application:
import "github.com/H0llyW00dzZ/FiberValidator"
Usage ¶
To use the validator middleware in a Fiber application, create a new instance of the middleware with the desired configuration and register it with the application.
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/H0llyW00dzZ/FiberValidator"
)
func main() {
app := fiber.New()
app.Use(validator.New(validator.Config{
Rules: []validator.Restrictor{
validator.RestrictUnicode{
Fields: []string{"name", "email"},
},
},
}))
// Register routes and start the server
// ...
app.Listen(":3000")
}
In the example above, a new instance of the validator middleware is created with a configuration that restricts the use of Unicode characters in the "name" and "email" fields of the request body.
Configuration ¶
The validator middleware accepts a validator.Config struct for configuration. The available options are:
- Rules: A slice of validator.Restrictor implementations that define the validation rules to be applied.
- Next: An optional function that determines whether to skip the validation middleware for a given request. If the function returns true, the middleware will be skipped.
- ErrorHandler: An optional custom error handler function that handles the error response. If not provided, the default error handler will be used.
Custom Validation Rules ¶
To define custom validation rules, implement the validator.Restrictor interface:
type Restrictor interface {
Restrict(c *fiber.Ctx) error
}
The Restrict method takes a Fiber context and returns an error if the validation fails.
Here's an example implementation that restricts the use of Unicode characters in specified fields:
type RestrictUnicode struct {
Fields []string
}
func (r RestrictUnicode) Restrict(c *fiber.Ctx) error {
// Parse the request body based on the Content-Type header
// ...
// Check each configured field for Unicode characters
// ...
return nil
}
Error Handling ¶
The validator middleware provides a default error handler that formats the error response based on the content type of the request. It supports JSON, XML, and plain text formats.
- For JSON requests, the error response is formatted as {"error": "Error message"}.
- For XML requests, the error response is formatted as <xmlError><error>Error message</error></xmlError>.
- For other content types, the error response is sent as plain text.
You can customize the error handling behavior by providing a custom error handler function in the ErrorHandler field of the validator.Config struct. The custom error handler should have the following signature:
func(c *fiber.Ctx, err error) error
Example custom error handler:
func customErrorHandler(c *fiber.Ctx, err error) error {
if e, ok := err.(*validator.Error); ok {
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{
"custom_error": e.Message,
})
}
return err
}
In this example, the custom error handler checks if the error is of type *validator.Error and returns a JSON response with a custom error format.
Index ¶
Constants ¶
const ( // ErrInvalidJSONBody represents an error message for an invalid JSON request body. ErrInvalidJSONBody = "Invalid JSON request body" // ErrUnicodeNotAllowedInField represents an error message for Unicode characters not allowed in a specific field. ErrUnicodeNotAllowedInField = "Unicode characters are not allowed in the '%s' field" // ErrInvalidXMLBody represents an error message for an invalid XML request body. ErrInvalidXMLBody = "Invalid XML request body" )
const ( // ErrFieldMustContainNumbersOnly represents an error message for a field that must contain only numbers. ErrFieldMustContainNumbersOnly = "The '%s' field must contain only numbers" // ErrFieldExceedsMaximumValue represents an error message for a field that exceeds the maximum allowed value. ErrFieldExceedsMaximumValue = "The '%s' field must not exceed %d" // ErrFieldExceedsMaximumDigits represents an error message for a field that exceeds the maximum allowed number of digits. ErrFieldExceedsMaximumDigits = "The '%s' field must not exceed %d digits" )
const ( // ErrFieldExceedsMaximumLength represents an error message for a field that exceeds the maximum allowed length. ErrFieldExceedsMaximumLength = "The '%s' field must not exceed %d characters" // ErrFieldsExceedMaximumLength represents an error message for fields that exceed the maximum allowed length. ErrFieldsExceedMaximumLength = "The '%s' fields must not exceed the maximum length" )
Variables ¶
var ConfigDefault = Config{ Rules: nil, Next: nil, ErrorHandler: DefaultErrorHandler, ContextKey: "", }
ConfigDefault is the default configuration for the Validator middleware.
Functions ¶
func DefaultErrorHandler ¶
DefaultErrorHandler is the default error handler function.
Types ¶
type Config ¶
type Config struct {
// Rules is a slice of Restrictor implementations to be used for validation.
Rules []Restrictor
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// ErrorHandler is a function that handles the error response.
//
// Optional. Default: DefaultErrorHandler
ErrorHandler func(c *fiber.Ctx, err error) error
// ContextKey is the key used to store the validation result in the context.
//
// Note: This is most useful in advanced use cases for communicating internal context within the application,
// especially for securing authentication and authorization.
//
// Optional. Default: nil
ContextKey string
}
Config defines the configuration for the Validator middleware.
type Error ¶
Error represents a validation error.
type RestrictNumberOnly ¶ added in v0.2.0
type RestrictNumberOnly struct {
// Fields specifies the fields to check for number-only validation.
Fields []string
// Max specifies the maximum allowed value for the fields (optional).
Max *int
// MaxDigits specifies the maximum number of digits allowed in the field value (optional).
MaxDigits *int
}
RestrictNumberOnly is a Restrictor implementation that restricts fields to contain only numbers and allows setting an optional maximum value and maximum number of digits.
type RestrictStringLength ¶ added in v0.5.0
type RestrictStringLength struct {
// Fields specifies the fields to check for string length validation.
Fields []string
// MaxLength specifies the maximum allowed length for the fields (optional).
MaxLength *int
}
RestrictStringLength is a Restrictor implementation that restricts the length of string fields and allows setting an optional maximum length.
type RestrictUnicode ¶
type RestrictUnicode struct {
// Fields specifies the fields to check for Unicode characters.
Fields []string
}
RestrictUnicode is a Restrictor implementation that restricts the use of Unicode characters in specified fields of the request body.
type Restrictor ¶
Restrictor is an interface for defining custom validation rules.