⚠️ Warning: This project is being tested so it's not ready for production use.
Valgopt provides a set of validators for the Valgo validation library that work seamlessly with optional value types from the Opt library.
This project extends Valgo's validation capabilities by providing validators specifically designed for Opt's optional types: omit.Val[T], null.Val[T], and omitnull.Val[T]. These validators replicate the functionality of Valgo's original validators while properly handling the optional nature of these types, allowing you to validate optional values in your Go applications with the same expressive and type-safe API that Valgo provides.
package main
import (
"fmt"
"github.com/aarondl/opt/null"
"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull"
"github.com/cohesivestack/valgo"
"github.com/cohesivestack/valgopt"
)
type User struct {
Age null.Val[int] // nullable field
Score omit.Val[int] // omitted when empty
Level omitnull.Val[int] // omitted when empty or null
}
func validateUser(user User) *valgo.ValidationSession {
return valgo.New().
Is(valgopt.NullInt(user.Age, "age").GreaterThan(0).LessThan(150)).
Is(valgopt.OmitInt(user.Score, "score").GreaterOrEqualTo(0).LessOrEqualTo(100)).
Is(valgopt.OmitNullInt(user.Level, "level").GreaterThan(0).LessOrEqualTo(10))
}
func main() {
// Example 1: Valid user
user1 := User{
Age: null.New(25),
Score: omit.New(85),
Level: omitnull.New(5),
}
validation := validateUser(user1)
if validation.Valid() {
fmt.Println("User is valid!")
} else {
fmt.Println("Validation errors:", validation.Errors())
}
// Example 2: Invalid user
user2 := User{
Age: null.New(200), // Invalid: too old
Score: omit.New(150), // Invalid: exceeds maximum
Level: omitnull.New(15), // Invalid: exceeds maximum
}
validation = validateUser(user2)
if !validation.Valid() {
fmt.Println("Validation errors:")
for field, errors := range validation.Errors() {
fmt.Printf(" %s: %v\n", field, errors)
}
}
// Example 3: Optional values (null/empty values are skipped)
user3 := User{
Age: null.Val[int]{}, // null - validation skipped
Score: omit.Val[int]{}, // empty - validation skipped
Level: omitnull.Val[int]{}, // empty - validation skipped
}
validation = validateUser(user3)
// All validations are skipped for null/empty optional values
fmt.Println("Optional values validation:", validation.Valid())
}This example demonstrates:
- Using
NullIntfor nullable integer values - Using
OmitIntfor integer values that are omitted when empty - Using
OmitNullIntfor integer values that are omitted when empty or null - How validators automatically skip validation for null/empty optional values
- The same expressive API as Valgo's standard validators
Copyright © 2025 Carlos Forero
Valgopt is released under the MIT License