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

情到浓时终转凉″ 提交于 2020-12-13 04:08:50

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/46400479/i-want-to-validate-timezone-at-the-backend-which-is-coming-from-the-frontend-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!