Skip to content

v.1.2.0

Choose a tag to compare

@buckedunicorn buckedunicorn released this 28 May 18:56
· 1 commit to main since this release
v1.2.0
e74ff88

📰 RELEASE NOTES (v1.1.0 - Validation)

Release Notes – v1.1.0

✅ Custom Preference Validation with ValidateFunc

UserPrefs now supports custom validation functions for each preference. You can define your own rules beyond basic type checking or allowed values.

How It Works

Each PreferenceDefinition can now include:

ValidateFunc: func(value interface{}) error

If the function returns an error, the preference value is rejected at Set() time.

Use Cases
• Enforcing integer or float value ranges
• Regex validation for emails, usernames, or URLs
• Checking structure and content of JSON preferences
• Implementing business rules (e.g., disallow localhost for API endpoints)

Example

{
    Key: "notification_email",
    Type: userprefs.StringType,
    DefaultValue: "",
    ValidateFunc: func(value interface{}) error {
        email := value.(string)
        if email != "" && !strings.Contains(email, "@") {
            return fmt.Errorf("invalid email format: %s", email)
        }
        return nil
    },
}

Examples Included
• 🧪 examples/basic: Adds simple validators for page count and email.
• 🧪 examples/validation: Full example suite showing how to test and design robust validation logic.

Best Practices
• Keep validators small and isolated per preference.
• Provide helpful, user-readable error messages.
• Use built-in types (string, int, map[string]interface{}) for safe assertions.
• Combine AllowedValues with ValidateFunc where needed.

Error Handling

If a value fails validation, Set() returns an error that wraps userprefs.ErrInvalidValue.

if errors.Is(err, userprefs.ErrInvalidValue) {
    log.Printf("Value rejected: %v", err)
}

⸻

This update makes it easy to define safe, application-specific rules for any preference, no matter how complex.