Go Validator

Transformers

The go-validator package provides a set of built-in transformers that allow you to modify or preprocess field values before validation. Transformers are applied sequentially to the value of a field, enabling you to clean, format, or convert data as needed.

How Transformers Work

  • Transformers are defined in the Transformers field of a ValidationOption.
  • Each transformer is a function that takes a value (interface{}) and returns a modified value (interface{}).
  • Transformers are applied before validation , ensuring that the validated value matches your desired format.

Using Transformers in Validation Rules

Transformers can be added to the Transformers field of a ValidationOption. They are applied in the order they are defined.

Example: Applying Multiple Transformers

validationOptions := []validator.ValidationOption{
    {
        Key: "username",
        Transformers: []validator.Transformer{
            validator.Trim,               // Remove leading/trailing whitespace
            validator.ToLower,            // Convert to lowercase
            validator.RemoveSpecialChars, // Remove special characters
        },
        Validators: []validator.Validator{
            validator.CreateValidator(validator.IsNotEmpty, "Username is required"),
            validator.CreateValidator(validator.IsAlphanumeric, "Username must be alphanumeric"),
        },
    },
}

In this example:

  1. The username field is trimmed of whitespace.
  2. It is converted to lowercase.
  3. Special characters are removed.
  4. Finally, it is validated to ensure it is not empty and is alphanumeric.

Built-in Transformers

Below is a list of the built-in transformers provided by the package:

String Manipulation

  1. ToLower

    • Converts a string to lowercase.
    • Example:
validator.Transformer(validator.ToLower)

Input: "HELLO" → Output: "hello"

ToUpper

  • Converts a string to uppercase.
  • Example:
validator.Transformer(validator.ToUpper)

Input: "hello" → Output: "HELLO"

  • Trim

    • Removes leading and trailing whitespace from a string.
    • Example:
validator.Transformer(validator.Trim)

Input: " hello " → Output: "hello"

RemoveSpecialChars

  • Removes special characters from a string, leaving only alphanumeric characters and spaces.
  • Example:
validator.Transformer(validator.RemoveSpecialChars)

Input: "Hello, World!" → Output: "Hello World"

ToTitleCase

  • Converts a string to title case (e.g., "hello world" → "Hello World").
  • Example:
validator.Transformer(validator.ToTitleCase)

Input: "hello world" → Output: "Hello World"

Truncate(maxLength int)

  • Truncates a string to a specified maximum length.
  • Example:
validator.Transformer(validator.Truncate(10))

Input: "hello world" → Output: "hello"

Replace(old, new string)

Replaces occurrences of a substring with another string. Example:

validator.Transformer(validator.Replace("hello", "hi"))

Input: "foo bar foo" → Output: "bar bar bar"

Type Conversion

ToInt

  • Converts a string or float to an integer.
  • Example:
validator.Transformer(validator.ToInt)

Input: "123" → Output: 123
Input: 123.45 → Output: 123

ToFloat

  • Converts a string or integer to a float.
  • Example:
validator.Transformer(validator.ToFloat)

Input: "123.45" → Output: 123.45
Input: 123 → Output: 123.0

Custom Transformers

You can also define your own custom transformers by implementing the Transformer type:

type Transformer func(value interface{}) interface{}

Example: Custom Transformer

// AddPrefix adds a prefix to a string.
func AddPrefix(prefix string) validator.Transformer {
    return func(value interface{}) interface{} {
        if str, ok := value.(string); ok {
            return prefix + str
        }
        return value
    }
}
 
// Usage in ValidationOption
validationOptions := []validator.ValidationOption{
    {
        Key: "code",
        Transformers: []validator.Transformer{
            AddPrefix("PREFIX-"), // Add a prefix to the value
        },
        Validators: []validator.Validator{
            validator.CreateValidator(validator.IsNotEmpty, "Code is required"),
        },
    },
}

Key Takeaways

  1. Preprocessing Data

    • Transformers allow you to clean, format, or convert data before validation.
    • They are particularly useful for normalizing input values.
  2. Built-in Transformers

    • The package provides a variety of built-in transformers for common use cases, such as string manipulation and type conversion.
  3. Custom Transformers

    • You can define custom transformers to handle specific requirements.
  4. Order of Execution

    • Transformers are applied sequentially in the order they are defined.

On this page