validate

package
v0.38.1 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package validate provides pure-function validators that return "" on success or a human-readable error message string on failure.

Index

Constants

View Source
const (
	MsgRequired          = "This field is required"
	MsgEmailInvalid      = "Invalid email address"
	MsgPhoneInvalid      = "Invalid phone number"
	MsgURLInvalid        = "Invalid URL"
	MsgMinLength         = "Too short"
	MsgMaxLength         = "Too long"
	MsgOneOf             = "Invalid selection"
	MsgIntRange          = "Value out of range"
	MsgMinAge            = "Does not meet minimum age requirement"
	MsgMaxAge            = "Exceeds maximum age"
	MsgPasswordWeak      = "Password is too weak"
	MsgHasUpper          = "Must contain an uppercase letter"
	MsgHasLower          = "Must contain a lowercase letter"
	MsgHasDigit          = "Must contain a digit"
	MsgHasSpecial        = "Must contain a special character"
	MsgValidatorNotFound = "Unknown validator"
)

Exported message constants used by the built-in validators. Override individual messages by using the *Msg function variants.

Variables

This section is empty.

Functions

func Email

func Email(value string) string

Email returns "" if value looks like a valid email, or MsgEmailInvalid.

func EmailMsg

func EmailMsg(value, msg string) string

EmailMsg is like Email with a custom message.

func EmptyOr

func EmptyOr(fn func(string) string) func(string) string

EmptyOr wraps a validator function so that empty (whitespace-only) values pass validation. Use this when a field is optional but must be valid if provided.

func HasDigit

func HasDigit(value string) string

HasDigit returns "" if value contains at least one digit, or MsgHasDigit.

func HasDigitMsg

func HasDigitMsg(value, msg string) string

HasDigitMsg is like HasDigit with a custom message.

func HasLower

func HasLower(value string) string

HasLower returns "" if value contains at least one lowercase letter, or MsgHasLower.

func HasLowerMsg

func HasLowerMsg(value, msg string) string

HasLowerMsg is like HasLower with a custom message.

func HasSpecial

func HasSpecial(value string) string

HasSpecial returns "" if value contains at least one special character (punctuation or symbol), or MsgHasSpecial.

func HasSpecialMsg

func HasSpecialMsg(value, msg string) string

HasSpecialMsg is like HasSpecial with a custom message.

func HasUpper

func HasUpper(value string) string

HasUpper returns "" if value contains at least one uppercase letter, or MsgHasUpper.

func HasUpperMsg

func HasUpperMsg(value, msg string) string

HasUpperMsg is like HasUpper with a custom message.

func IntRange

func IntRange(value int, min, max int) string

IntRange returns "" if value is between min and max (inclusive), or MsgIntRange.

func IntRangeMsg

func IntRangeMsg(value, min, max int, msg string) string

IntRangeMsg is like IntRange with a custom message.

func MaxAge

func MaxAge(birthDate string, maxAge int) string

MaxAge returns "" if the person with the given birthDate (YYYY-MM-DD) is at most maxAge years old, or MsgMaxAge.

func MaxAgeMsg

func MaxAgeMsg(birthDate string, maxAge int, msg string) string

MaxAgeMsg is like MaxAge with a custom message.

func MaxLength

func MaxLength(value string, max int) string

MaxLength returns "" if value has at most max runes, or MsgMaxLength.

func MaxLengthMsg

func MaxLengthMsg(value string, max int, msg string) string

MaxLengthMsg is like MaxLength with a custom message.

func MinAge

func MinAge(birthDate string, minAge int) string

MinAge returns "" if the person with the given birthDate (YYYY-MM-DD) is at least minAge years old, or MsgMinAge.

func MinAgeMsg

func MinAgeMsg(birthDate string, minAge int, msg string) string

MinAgeMsg is like MinAge with a custom message.

func MinLength

func MinLength(value string, min int) string

MinLength returns "" if value has at least min runes, or MsgMinLength.

func MinLengthMsg

func MinLengthMsg(value string, min int, msg string) string

MinLengthMsg is like MinLength with a custom message.

func NormalizeURL

func NormalizeURL(value string) string

NormalizeURL prepends "https://" when value has no scheme. Returns the original value unchanged if it is empty or already has a scheme.

func OneOf

func OneOf(value string, options ...string) string

OneOf returns "" if value is one of the allowed options, or MsgOneOf.

func OneOfMsg

func OneOfMsg(value, msg string, options ...string) string

OneOfMsg is like OneOf with a custom message.

func PasswordStrength

func PasswordStrength(password string) string

PasswordStrength returns "" if all password requirements are met, or MsgPasswordWeak.

func PasswordStrengthMsg

func PasswordStrengthMsg(password, msg string) string

PasswordStrengthMsg is like PasswordStrength with a custom message.

func Phone

func Phone(value string) string

Phone returns "" if value is a plausible phone number, or MsgPhoneInvalid. It accepts optional leading '+' followed by 7-15 digits.

func PhoneMsg

func PhoneMsg(value, msg string) string

PhoneMsg is like Phone with a custom message.

func Register

func Register(name string, fn func(string) string)

Register adds a named validator function to the global registry.

func Required

func Required(value string) string

Required returns "" if value is non-empty, or MsgRequired.

func RequiredMsg

func RequiredMsg(value, msg string) string

RequiredMsg is like Required with a custom message.

func Run

func Run(name, value string) string

Run executes a registered validator by name. If the name is not found it returns MsgValidatorNotFound.

func RunRules

func RunRules(value string, rules ...Rule) string

RunRules executes rules in order, returning the first error message. Returns "" if all rules pass.

func URL

func URL(value string) string

URL returns "" if value is a valid absolute URL, or MsgURLInvalid.

func URLMsg

func URLMsg(value, msg string) string

URLMsg is like URL with a custom message. Only http/https URLs are accepted: a validated URL frequently lands in an href/src, and schemes like javascript:, data:, and vbscript: are XSS vectors. Note "javascript://x/..." parses with both a scheme and a host, so a scheme allowlist (not just a non-empty-scheme check) is required to reject it.

Types

type CtxRule

type CtxRule = func(echo.Context, string) string

CtxRule is a context-aware validation function that receives the Echo context alongside the value. Useful for cross-field comparisons (e.g. password confirmation) or checking request-scoped data.

type FieldBuilder

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

FieldBuilder defines a field's validation rules and satisfies FormOption. Use Field or FieldMsg to create one.

func Field

func Field(name string, rules ...Rule) FieldBuilder

Field defines a field with rules that use each rule's default error message.

func FieldMsg

func FieldMsg(name, msg string, rules ...Rule) FieldBuilder

FieldMsg defines a field where any rule failure produces the given message, regardless of which rule failed.

func (FieldBuilder) WithCtx

func (fb FieldBuilder) WithCtx(rules ...CtxRule) FieldBuilder

WithCtx adds context-aware rules to the field. These run after standard rules and only if all standard rules pass.

Note: WithTrim only trims the current field's value before it is passed to rules. Values read from echo.Context inside a CtxRule (e.g. c.FormValue("other_field")) are untrimmed. Apply strings.TrimSpace manually if cross-field comparisons need consistent trimming.

func (FieldBuilder) WithRenderer

func (fb FieldBuilder) WithRenderer(fn FieldRenderer) FieldBuilder

WithRenderer sets a custom renderer for this field's per-field validation. Falls back to the form-level WithOOBRenderer if not set.

type FieldRenderer

type FieldRenderer func(c echo.Context, field, errMsg string) error

FieldRenderer renders a per-field validation result. Used by ValidationHandler to produce the HTTP response (typically an OOB swap).

type Form

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

Form holds field rule definitions for both full-form validation and HTMX per-field validation. Define rules once in the constructor; use Validate for full-form checks and ValidationHandler for per-field HTMX endpoints.

func NewForm

func NewForm(opts ...FormOption) Form

NewForm creates a Form from the given options and field definitions.

func (Form) Validate

func (f Form) Validate(c echo.Context) map[string]string

Validate runs all field rules against form values from the Echo context. Returns a map of field name to error message, or nil if all fields pass.

Per-field short-circuit is always on: rules for a single field stop at the first failure. Per-form short-circuit is controlled by WithShortCircuit.

func (Form) ValidationHandler

func (f Form) ValidationHandler(paramName string) echo.HandlerFunc

ValidationHandler returns an echo.HandlerFunc that validates a single field. The paramName argument is the Echo route parameter name that contains the field name (e.g. "field" for ":field").

Unknown fields are silently ignored — the handler returns an empty/no-error response via the renderer.

type FormOption

type FormOption interface {
	// contains filtered or unexported methods
}

FormOption configures a Form via NewForm.

func WithGeneralError

func WithGeneralError(msg string) FormOption

WithGeneralError adds a message under the "general" key in the error map when any field fails validation. Templates display it via form.GetError(errs, "general").

func WithOOBRenderer

func WithOOBRenderer(fn FieldRenderer) FormOption

WithOOBRenderer sets the default renderer used by ValidationHandler to produce per-field error responses.

func WithShortCircuit

func WithShortCircuit(on bool) FormOption

WithShortCircuit stops validating after the first field that fails. Default is false — all fields are validated and all errors returned.

func WithTrim

func WithTrim(on bool) FormOption

WithTrim enables automatic whitespace trimming of form values before validation.

type PasswordRequirement

type PasswordRequirement struct {
	Description string
	Met         bool
}

PasswordRequirement describes a single password rule and whether it is met.

func CheckPasswordRequirements

func CheckPasswordRequirements(password string) []PasswordRequirement

CheckPasswordRequirements evaluates password against common strength rules and returns the status of each requirement.

type Rule

type Rule = func(string) string

Rule is a pure validation function: returns "" on success or an error message on failure. This is a type alias so existing validators like Required and Email satisfy it without casting.

func AgeMax

func AgeMax(maxAge int) Rule

AgeMax returns a rule that checks a birth date (YYYY-MM-DD) does not exceed a maximum age.

func AgeMin

func AgeMin(minAge int) Rule

AgeMin returns a rule that checks a birth date (YYYY-MM-DD) meets a minimum age requirement.

func In

func In(options ...string) Rule

In returns a rule that checks the value is one of the allowed options.

func MaxLen

func MaxLen(n int) Rule

MaxLen returns a rule that checks the value has at most n runes.

func MinLen

func MinLen(n int) Rule

MinLen returns a rule that checks the value has at least n runes.

func WithMsg

func WithMsg(rule Rule, msg string) Rule

WithMsg wraps a rule so that any non-empty result is replaced with msg.

Jump to

Keyboard shortcuts

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