2017-07-26 10:35
浏览 121

使用验证V2 Golang软件包的正则表达式电话号码不起作用

I am having some trouble when using to validate regex some phone numbers with this prefix +62, 62, 0, for instance number e.g. +628112blabla, 0822blablabla, 628796blablabla.

I have try my regex on online regex tester and no issue with the regex on that. Here the regex is :


But when I try with my go implement with it, the regex not working. This is my code for implement the purpose :

type ParamRequest struct {
    PhoneNumber string `validate:"nonzero,regexp=(0|\+62|062|62)[0-9]+$"`
    ItemCode    string `validate:"nonzero"`
    CallbackUrl string `validate:"nonzero"`

func (c *TopupAlloperatorApiController) Post() {
    var v models.TopupAlloperatorApi

    interf := make(map[string]interface{})

    json.Unmarshal(c.Ctx.Input.RequestBody, &interf)

    logs.Debug(" Json Input Request ", interf)
    var phone, item, callback string

    if _, a := interf["PhoneNumber"].(string); a {
        phone = interf["PhoneNumber"].(string)
    if _, b := interf["ItemCode"].(string); b {
        item = interf["ItemCode"].(string)

    if _, c := interf["CallbackUrl"].(string); c {
        callback = interf["CallbackUrl"].(string)

    ve := ParamRequest{
        PhoneNumber: phone,
        ItemCode:    item,
        CallbackUrl: callback,

    logs.Debug(" Param Request ", ve)

    err := validator.Validate(ve)
    if err == nil {
      // not success

Many thanks for anything help. Thank you.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doudou32012 2017-07-31 10:43

    Because you are using regexp to check PhoneNumber that won't be matching if the value is empty it is better to remove nonzero from the validation.
    I have checked out documentation and haven't found examples where you can use both: nonzero and regexp.
    Also you need to make your regex symbol-escaped, otherwise it won't be detected by reflection. It means you should use (0|\\+62|062|62)[0-9]+$ in your code. Here is example where problem is: symbol escaping in struct tags
    And also, please try to use this regexp: ^\\+{0,1}0{0,1}62[0-9]+$

    解决 无用
    打赏 举报