Home  >  Article  >  Backend Development  >  ozzo validation in rules returns error for equal values

ozzo validation in rules returns error for equal values

WBOY
WBOYforward
2024-02-05 22:48:03835browse

规则中的 ozzo 验证对于相等值返回错误

Question content

I have a simple code that uses echo as the engine and ozzo-validation Act as a request validator.

func (a MyRequest) Validate() error {
    return validation.ValidateStruct(
        &a,
        validation.Field(&a.Value,
            validation.Required,
            validation.Length(1, 5),
            validation.Each(validation.NilOrNotEmpty, validation.In([]string{"true", "false"}),
            ),
        ),
    )
}

This is the request I sent:

{"value":["true"]}

I'm getting this error from In rules:

value: (0: must be a valid value.).

But when I check the value using == and reflect.DeppEqual, the values ​​are equal:

fmt.Println(reflect.DeepEqual([]string{"true", "false"}[0], a.Value[0]))
fmt.Println([]string{"true", "false"}[0] == a.Value[0])


output:
true
true

What am I doing wrong here?


Correct answer


Use validation.Each(validation.In([]string{"true", "false"})) Yes Compares each element in the Value slice to the slice provided to validate.In, i.e. []string{ "true", "false"} .

Use validation.In("true", "false") to compare each element in the Value slice with each value in validate.In Compare.

The above is the detailed content of ozzo validation in rules returns error for equal values. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete