Constraints

Constraints

The validation is designed to validate data against constraints.

Import

import (
	"gitnet.fr/deblan/go-form/validation"
)

Constraints

Length

Validate the length of an array, a slice or a string

c := validation.NewLength()

// Define minimum
c.WithMin(1)

// Define minimum
c.WithMax(100)

// Define min and max
// Equivalent to c.WithMin(50).WithMax(50)
c.WithExact(50)

Mail

validation.NewMail()

Not blank

validation.NewNotBlank()

Range

Validate a number

c := validation.NewRange()

// Define minimum
c.WithMin(1)

// Define minimum
c.WithMax(100)

// Define min and max
// Equivalent to c.WithMin(1).WithMax(100)
c.WithRange(1, 100)

Regex

Validate a string with a regex

c := validation.NewRegex(`expression`)

// The value must match
c.MustMatch()

// The value must not match
c.MustNotMatch()

Is even

Validate that a number is even.

validation.NewIsEven()

Is odd

Validate that a number is odd.

validation.NewIsOdd()

Custom constraint

Use case: you want to validate that the data equals “example”

package validation

import (
	"reflect"

	v "gitnet.fr/deblan/go-form/validation"
)

// Define a struct
type IsExample struct {
	Message          string
	TypeErrorMessage string
}

// Create a factory
func NewIsExample() IsEven {
	return IsEven{
		Message:          "This value does not equal \"example\".",
		TypeErrorMessage: "This value can not be processed.",
	}
}

// Implement the validation
func (c IsExample) Validate(data any) []Error {
	errors := []Error{}

    // Should not validate blank data
    if len(v.NewNotBlank().Validate(data)) != 0 {
		return []Error{}
	}

	t := reflect.TypeOf(data)

	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	switch t.Kind() {
	case reflect.String:
		if data.(string) != "example" {
    		errors = append(errors, Error(c.Message))
        }

	default:
		errors = append(errors, Error(c.TypeErrorMessage))
	}

    return errors
}