GoLang Validator Non-Required Fields Returns Error

Viewed 153

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 Answers

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...

Related