go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.14k stars 1.29k forks source link

Best way to combine string, built in tag and custom tag? #1143

Closed onattech closed 7 months ago

onattech commented 11 months ago

Package version:

v10

Issue, Question or Enhancement:

What is the best way to combine built and tags with my custom tags? I need to setup a validation for acceptable extensions. Which are pdf, zip, image, video.

So, pdf and zip will be string values, image will be the built in image tag, and video will be a custom tag I need to build with mov,mkv,mpg,mp4

What is the best way to combine these?

Thank you

deankarn commented 11 months ago

If you mean for the same field into one then you can register an alias which combines one or more individual validation tags into one https://github.com/go-playground/validator/blob/master/validator_instance.go#L251

onattech commented 11 months ago

Thank you for the quick response. Here's what I got. Video extensions do work but image extensions don't. I was hoping built in image tag would work here.

    // video (common video formats)
    _ = validate.RegisterValidation("video", func(fl validator.FieldLevel) bool {
        return regexp.MustCompile(`(?i)(mp4|avi|mkv|flv|mov|wmv)$`).MatchString(fl.Field().String())
    })

    validate.RegisterAlias("extension", "video|image")
onattech commented 11 months ago

Ok, I just test the image tag by itself and I can't get it to work. I am trying both image/bmp and bmp, no avail.

Here's how I am declaring it

Extension string `validate:"required,image"`
onattech commented 11 months ago

Assigned the image tag manually and it all work now.

    _ = validate.RegisterValidation("image", func(fl validator.FieldLevel) bool {
        return regexp.MustCompile(`(?i)(bmp|gif|ief|jpeg|jpg|png|svg|tiff|webp)$`).MatchString(fl.Field().String())
    })