Prince Raj
Prince Raj

Reputation: 33

I want to validate timezone at the backend which is coming from the frontend in golang

The front-end is sending timezones along with other user details during sign up. I need to put a validator on timezone for api testing. The data in the timezone is of the format:

(GMT-10:00) Hawaii
(GMT-08:00) Pacific Time (US & Canada)

What I did is define all the timezones in an array and then search for the received timezone. If it exists then ok else return err. My function is:

func timeZoneValidator(field validator.FieldLevel) bool {
    if field.Field().Kind() != reflect.String {
        return false
    }
    timeZoneField := field.Field().String()

    for i:= range timeZones {
        if timeZones[i] == timeZoneField {
            // Found!
            return true
        }
    }
    return false
}

But I want to use a library or something that does this task for me. If you got any, please advise.

Upvotes: 2

Views: 2245

Answers (2)

cnicutar
cnicutar

Reputation: 182694

You might be able to use time.LoadLocation.

func LoadLocation(name string) (*Location, error)

You can pass in a string such as "America/New_York" and the error return should tell you if it's valid.

Note the format will be different from what you currently have. Check out https://www.iana.org/time-zones

Upvotes: 6

Nima Ghotbi
Nima Ghotbi

Reputation: 671

I don't know if there is a library for this, but you can optimize the code by using a map insist of the array, so u don't have to iterate over it.

_, ok := timeZones[timeZoneField]
return ok

Upvotes: -1

Related Questions