asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.04k stars 555 forks source link

Empty email to success when optional #385

Closed sodefrin closed 4 years ago

sodefrin commented 4 years ago

I fixed this issue https://github.com/asaskevich/govalidator/issues/368.

In PR https://github.com/asaskevich/govalidator/pull/329, 2 changes were made.

(1) If the field is required, only nil value is treated as invalid and skips other validations. (2) If the field is optional, nil value skip validations. The empty values doesn't skip validation.

Because of (2), below example is not working. A empty email become invalid.

// lastly, this will only fail when Email is an invalid email address but not when it's empty:
type exampleStruct2 struct {
  Name  string `valid:"-"`
  Email string `valid:"email,optional"`
}

So I made changes below.

(1) If the field is optional, nil and empty value is valid (skip other validation). (2) If the field is required, only nil values is treated as invalid and skip other validation.

I'm not sure this is the best way to do it, but I hope you'll consider it.

(Maybe we should fix it so that only nil is treated as "zero value" when it is a pointer type)

nmccready commented 4 years ago

Why was this closed?

dumim commented 3 years ago

Yes why is this closed? The optional tag does not work with email as mentioned in the README