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 aValidationOption
. - 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
In this example:
- The
username
field is trimmed of whitespace. - It is converted to lowercase.
- Special characters are removed.
- 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
-
ToLower
- Converts a string to lowercase.
- Example:
Input: "HELLO"
→ Output: "hello"
ToUpper
- Converts a string to uppercase.
- Example:
Input: "hello"
→ Output: "HELLO"
-
Trim
- Removes leading and trailing whitespace from a string.
- Example:
Input: " hello "
→ Output: "hello"
RemoveSpecialChars
- Removes special characters from a string, leaving only alphanumeric characters and spaces.
- Example:
Input: "Hello, World!"
→ Output: "Hello World"
ToTitleCase
- Converts a string to title case (e.g., "hello world" → "Hello World").
- Example:
Input: "hello world"
→ Output: "Hello World"
Truncate(maxLength int)
- Truncates a string to a specified maximum length.
- Example:
Input: "hello world"
→ Output: "hello"
Replace(old, new string)
Replaces occurrences of a substring with another string. Example:
Input: "foo bar foo"
→ Output: "bar bar bar"
Type Conversion
ToInt
- Converts a string or float to an integer.
- Example:
Input: "123"
→ Output: 123
Input: 123.45
→ Output: 123
ToFloat
- Converts a string or integer to a float.
- Example:
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:
Example: Custom Transformer
Key Takeaways
-
Preprocessing Data
- Transformers allow you to clean, format, or convert data before validation.
- They are particularly useful for normalizing input values.
-
Built-in Transformers
- The package provides a variety of built-in transformers for common use cases, such as string manipulation and type conversion.
-
Custom Transformers
- You can define custom transformers to handle specific requirements.
-
Order of Execution
- Transformers are applied sequentially in the order they are defined.