go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

Validate boolean values #79

Closed Narven closed 4 years ago

Narven commented 5 years ago

Is there a way to validate boolean values?

Thanks

rafa-acioly commented 4 years ago

@Narven you can just use the typing of a struct; what exactly you want to validate?

type Content struct {
    Enabled bool `json:"enabled"`
}
Narven commented 4 years ago
// ValidateUpdateResponseBody Provides validation for the response body on Update
func (s Stream) ValidateUpdateResponseBody() error {
    return validation.ValidateStruct(&s,
        validation.Field(&s.Title, validation.Required, validation.Length(2, 80)),
        validation.Field(&s.IsActive),
    )
}

I would like to stay that the validation.Field(&s.IsActive), is optional... but if is there.. it needs to be true or false

Any ideas? thanks

Narven commented 4 years ago

I dont like using structs for that. Because a validation is never the same base on different conditions. If a struct on creation has some fields that are valid, the do not need to be valid when updating. or on delete

Unless you do stuff like

type ContentOnUpdate struct {
}

type ContentOnCreate struct {
}

type ContentOnSunset struct {
}

type ContentOnChristmas struct {
}

type ContentOnDelete struct {
}
rafa-acioly commented 4 years ago

@Narven if the content is different for each action is better to create a struct like you show, when you use;

type Content struct {
    Enabled bool `json:"enabled"`
}

the field enabled is already optional and if the payload has the key then it will be parsed, if the enabled is not passed the default is False, i don't think that you need a validator for true/false.

qiangxue commented 4 years ago

As answered above, you don't need to validate a value is a boolean if its type is bool. If you want to validate if a value is true, then use the Required rule.