6

I'm using GoLang Validator on a struct to validate its fields. Even though I don't add required tag, it still behaves as if it is required.

type Order struct {
    // ... other fields
    UserID string `json:"userId" validate:"uuid4"`
    // ... other fields
}

if err = validator.New().Struct(i); err != nil {
    return err
}

Output: User ID: unknown error

It is not required hence the value is zero-value but it still returns an error. Am I doing something wrong here?

1 Answer 1

6

You should add the omitempty validator to allow empty values. Try out the code below on Go playground.

    type Order struct {
        // ... other fields
        UserID string `json:"omitempty,userId" validate:"omitempty,uuid4"`
        // ... other fields
    }

    if err := validator.New().Struct(Order{}); err != nil {
        return err
    }

Note that to marshal the struct to JSON you also need to set the omitempty validator if you want to allow empty values...

Sign up to request clarification or add additional context in comments.

2 Comments

omitempty doesn't work. I still get an error Password field failed on the min tag. The field is optional but if specified, needs to have its length with a range (min=8,max=25)
It does work fine when I try it: go.dev/play/p/aJ6b15hBqSr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.