Skip to content

Conditional Validation #216

@pcfreak30

Description

@pcfreak30

Need a way to define schema's to be conditional based on other properties values.

Like enforce Y if X is true.

// Schema returns the Zog validation schema for RateLimitConfig.
func (c RateLimitConfig) Schema() zog.ZogSchema {
	return zog.Struct(zog.Shape{
		"Enabled":   zog.Bool().Optional(),
		"Rate":      zog.Float64().Optional(),
		"Burst":     zog.Int().Optional(),
		"ExpiresIn": zog.Duration().Optional(),
	}).TestFunc(func(valPtr *RateLimitConfig, ctx z.Ctx) bool {
		// Only validate rate limiting fields if rate limiting is enabled
		if !valPtr.Enabled {
			return true
		}
		
		// Validate Rate
		if valPtr.Rate <= 0 {
			ctx.AddIssue(zog.ZogIssue{
				Code:    zconst.ZogIssueCode("rate_invalid"),
				Path:    []string{"Rate"},
				Message: "rate must be greater than 0 when rate limiting is enabled",
				Value:   valPtr.Rate,
			})
			return false
		}
		if valPtr.Rate > 1000 {
			ctx.AddIssue(zog.ZogIssue{
				Code:    zconst.ZogIssueCode("rate_invalid"),
				Path:    []string{"Rate"},
				Message: "rate must be less than 1000 requests per second",
				Value:   valPtr.Rate,
			})
			return false
		}
		
		// Validate Burst
		if valPtr.Burst <= 0 {
			ctx.AddIssue(zog.ZogIssue{
				Code:    zconst.ZogIssueCode("burst_invalid"),
				Path:    []string{"Burst"},
				Message: "burst must be greater than 0 when rate limiting is enabled",
				Value:   valPtr.Burst,
			})
			return false
		}
		
		// Validate ExpiresIn
		if valPtr.ExpiresIn <= 0 {
			ctx.AddIssue(zog.ZogIssue{
				Code:    zconst.ZogIssueCode("expires_in_invalid"),
				Path:    []string{"ExpiresIn"},
				Message: "expires_in must be greater than 0 when rate limiting is enabled",
				Value:   valPtr.ExpiresIn,
			})
			return false
		}
		if valPtr.ExpiresIn > 24*time.Hour {
			ctx.AddIssue(zog.ZogIssue{
				Code:    zconst.ZogIssueCode("expires_in_invalid"),
				Path:    []string{"ExpiresIn"},
				Message: "expires_in must be less than 24 hours",
				Value:   valPtr.ExpiresIn,
			})
			return false
		}
		
		return true
	}, z.Message("rate limiting configuration validation failed"))
}

Having to do this ATM.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions