douzong5473 2017-07-26 10:35
浏览 125
已采纳

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

I am having some trouble when using github.com/go-validator/validator 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 :

(0|\+62|062|62)[0-9]+$

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 {
       //success
    }else{
      // 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]+$

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致