go-validator/validator

`omitempty` support

Closed this issue · 3 comments

Hello,

Is there any built-in omitempty definition?

What would omitempty do exactly?

No validation is executed if omitempty is passed as the last parameter.

I'm building a CLI app and the user can either, say, pass an --id parameter to a command that will either list a bunch of blogposts or just the one with the given ID. The idea is to validate --id if it's not empty as if it looks like an UUID but if it contains omitempty then the value becomes optional.

Right now what I have is a mix between nonzero and then a custom uuidv4 validator. In order to make the --id field required I say validate:"nonzero,uuidv4" but UUIDv4 has to not return an error if the string is empty. If I could just couple omitempty at the end, all previous validations could be omitted unless the string is not empty.

Hope that explains it with a use case scenario.

Instead of making a new flag, you can just make your custom uuidv4 validator return valid if the string is empty or if it is a valid uuid value.