form_validator

package module
v0.0.0-...-b9e69ce Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2025 License: MIT Imports: 9 Imported by: 0

README

Form Validator

A simple yet powerful form validation package for Go web applications.

Features

  • String validation (required, email, length checks, in slice, matches ...)
  • Integer validation
  • Boolean validation
  • File upload validation (size, type, extension)
  • Custom validation rules
  • HTTP form integration
  • Built-in validation for common image formats

Installation

go get github.com/yourusername/form_validator

Basic Usage

func handleForm(w http.ResponseWriter, r *http.Request) {
    // Create validator from HTTP request.
    v := form_validator.NewHTTP(r)
    
    // Validate form fields.
    username := v.String("username", form_validator.Required, form_validator.MinLength(3))
    email := v.String("email", form_validator.Required, form_validator.Email)
    age := v.Int("age")
    
    // Validate file upload.
    config := form_validator.ImageConfig(1 * form_validator.MB)
    avatar := v.Image("avatar", config)
    
    if !v.Valid() {
        // Handle validation errors.
        return
    }
    
    // Process valid form...
    fmt.Println(username, email, age, avatar)
}
Custom Validation Rules
// Create custom validation function.
isValidUsername := Custom(
    func(value string) bool {
        // Add your custom validation logic.
        return len(value) >= 3 && !strings.Contains(value, " ")
    },
    "Username must be at least 3 characters and contain no spaces",
)

// Use custom validation.
username := v.String("username", form_validator.Required, isValidUsername)
File Upload Validation
func handleImageUpload(w http.ResponseWriter, r *http.Request) {
    v := form_validator.NewHTTP(r)
    
    // Configure image validation.
    config := form_validator.ImageConfig(
        5 * form_validator.MB,  // Max size: 5MB.
        "jpg", "png", "webp",  // Allowed formats.
    )
    
    // Validate the uploaded image.
    file := v.Image("profile_picture", config)
    if !v.Valid() {
        // Handle validation errors.
        fmt.Println(v.Errors["profile_picture"])
        return
    }
    
    // Process valid file...
}

Best Practices

  1. Always check v.Valid() before processing form data
  2. Use appropriate validation functions for each field type
  3. Set reasonable file size limits for uploads
  4. Validate file types and extensions for security
  5. Handle validation errors appropriately in your application

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	MimeJPEG = "image/jpeg"
	MimePNG  = "image/png"
	MimeGIF  = "image/gif"
	MimeWEBP = "image/webp"
)

Common MIME types for images.

View Source
const (
	KB = 1024
	MB = 1024 * KB
)

Common file size constants.

Variables

View Source
var DefaultImageFormats = []string{"jpg", "jpeg", "png", "gif", "webp"}

Default image formats.

Functions

func Boolean

func Boolean(field, value string) (bool, string)

Boolean validates that a value is "true" or "false"

func Email

func Email(field, value string) (bool, string)

Email validates email format

func Required

func Required(field, value string) (bool, string)

Required validates that a field is not empty

Types

type FileValidationConfig

type FileValidationConfig struct {
	MaxSize      int64    // maximum file size in bytes.
	AllowedTypes []string // allowed MIME types.
	AllowedExts  []string // allowed file extensions.
}

Add new types and constants for file validation.

func ImageConfig

func ImageConfig(maxSize int64, formats ...string) FileValidationConfig

ImageConfig creates a standard image validation configuration.

type HTTPValidator

type HTTPValidator struct {
	*Validator
	// contains filtered or unexported fields
}

HTTPValidator extends Validator to work with http.Request.

func NewHTTP

func NewHTTP(r *http.Request) *HTTPValidator

NewHTTP creates a new HTTP validator.

type ValidationFunc

type ValidationFunc func(field, value string) (bool, string)

ValidationFunc represents a validation function.

func Custom

func Custom(check func(string) bool, message string) ValidationFunc

Custom creates a validation function from a custom check.

func InStringSlice

func InStringSlice(slice []string) ValidationFunc

InStringSlice creates a validation function that checks if a value exists in a slice.

func IntRange

func IntRange(min, max int) ValidationFunc

IntRange creates a validation function for integer range.

func Matches

func Matches(pattern string, message string) ValidationFunc

Matches creates a validation function for regex pattern matching

func MaxLength

func MaxLength(max int) ValidationFunc

MaxLength creates a validation function for maximum length

func MinLength

func MinLength(min int) ValidationFunc

MinLength creates a validation function for minimum length

type Validator

type Validator struct {
	Errors map[string]string
	// contains filtered or unexported fields
}

Validator holds the validation errors and form values.

func New

func New() *Validator

New creates a new validator instance.

func (*Validator) Check

func (v *Validator) Check(ok bool, field, message string)

Check adds an error if the condition is false.

func (*Validator) GetFile

func (v *Validator) GetFile(field string) *multipart.FileHeader

Add method to get file.

func (*Validator) GetValue

func (v *Validator) GetValue(field string) string

GetValue gets a form value.

func (*Validator) Image

func (v *Validator) Image(field string, config FileValidationConfig) *multipart.FileHeader

Image validates an image file field.

func (*Validator) Int

func (v *Validator) Int(field string, validations ...ValidationFunc) int64

Int validates and returns an integer field.

func (*Validator) SetFile

func (v *Validator) SetFile(field string, file *multipart.FileHeader)

Add method to set file.

func (*Validator) SetValue

func (v *Validator) SetValue(field, value string)

SetValue sets a form value.

func (*Validator) String

func (v *Validator) String(field string, validations ...ValidationFunc) string

String validates a string field with the given validation functions

func (*Validator) Valid

func (v *Validator) Valid() bool

Validate returns true if there are no errors.

Jump to

Keyboard shortcuts

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