RapidGo
No results found

Validation

Validate request input with a fluent, chainable API.

RapidGo provides a fluent validation API for validating form and API input.

Basic Usage

import "github.com/RAiWorks/RapidGo/v2/core/validation"

func SubmitContact(c *gin.Context) {
    name := c.PostForm("name")
    email := c.PostForm("email")
    message := c.PostForm("message")

    v := validation.New()
    v.Required("name", name)
    v.Required("email", email).Email("email", email)
    v.Required("message", message).MinLength("message", message, 10)

    if !v.Valid() {
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "errors": v.Errors(),
        })
        return
    }

    // Input is valid, proceed...
}

Available Rules

Method Description
Required(field, value) Value must not be empty
MinLength(field, value, min) Minimum character count
MaxLength(field, value, max) Maximum character count
Email(field, value) Valid email format
URL(field, value) Must start with http:// or https://
Matches(field, value, pattern) Regex pattern match
In(field, value, allowed) Value must be in allowed list
Confirmed(field, value, confirmation) Two values must match
IP(field, value) Valid IP address

Chaining

All methods return *Validator, so you can chain rules:

v.Required("email", email).Email("email", email).MaxLength("email", email, 255)

Error Format

v.Errors() returns a map[string][]string:

{
    "name": ["name is required"],
    "email": ["email must be a valid email"],
    "message": ["message must be at least 10 characters"]
}

In Templates

{{ if .errors }}
    {{ with index .errors "email" }}
        {{ range . }}<p class="error">{{ . }}</p>{{ end }}
    {{ end }}
{{ end }}