草庐IT

validation - Golang 验证器多字段依赖

coder 2024-07-07 原文

我想验证以下结构:

type CarModel struct {
  gorm.Model
  OwnerID    int    `json:"ownerid" validate:"nonzero"`
  Type       string `json:"type" validate:"regexp=(?)(A|B)"`
  A        string `json:"url" validate:"isurl"`
  B         string `json:"ip" validate:"isip"`
}

我想根据类型验证 A 和 B, 如果 type = A 那么 A 必须存在并且必须是一个 URL BUT 不能存在 如果 type = B 那么 A 一定不存在并且 B 必须是一个 IP

验证器可以吗?

我确实尝试过自定义验证,但我找不到查看类型值的方法:

func checkB(v interface{}, param string) error {
    theB := reflect.ValueOf(v)
    if theB.Kind() != reflect.String {
        return validator.ErrUnsupported
    }
    //check if B is an IP
    ipcool := net.ParseIP(theB.String())
    if ipcool == nil {
        return errors.New("B : ip incorrecte " + theB.String())
    }
    return nil
}

根据Alex Nichol的回答,首先感谢您的帮助。

如果我理解正确,我将不得不遍历所有“验证”字段,以跟踪 TYPE、A 和 B 的值,然后根据 TYPE 检查它们 ...

我这样做了:

func checkMonitor(v interface{}) error {
    var mytype string
    var myA string
    var myB string

    val := reflect.ValueOf(v)
    // Iterate through fields
    for i := 0; i < val.NumField(); i++ {
        // Lookup the validate tag
        field := val.Type().Field(i)
        tags := field.Tag
        _, ok := tags.Lookup("validate")
        if !ok {
            // No validate tag.
            continue
        }

        // Get the value of the field.
        fieldValue := val.Field(i)

        switch field.Name {
        case "Type":
            mytype = fieldValue.Interface()
        case "A":
            myA = fieldValue.Interface()
        case "B":
            myB = fieldValue.Interface()
        }
        // Validation logic here.
        //fmt.Println("field", field.Name, "has validate tag", validate, "and value", fieldValue.Interface())
    }
    if mytype == "A" {
        if myA == "" {
            return errors.New("A vide et type A")
        }
        ipcool := net.ParseIP(myA)
        if ipcool == nil {
            return errors.New("A incorrecte " + myA)
        }
    } else if mytype == "HTML" {
        if myB == "" {
            return errors.New("B vide et type B")
        }
        _, urlpascool := url.ParseRequestURI(myB)
        if urlpascool != nil {
            return errors.New("B incorrecte " + myB)
        }
    }
    return nil
}

但在 switch case 的 mytype、myA 和 myB 上出现错误:

不能在赋值中使用 fieldValue.Interface()(类型接口(interface) {})作为类型字符串:需要类型断言

编辑: 只需要使用我的大脑:

switch field.Name {
case "Type":
   mytype = fieldValue.String()
case "A":
   myA = fieldValue.String()
case "B":
   myB = fieldValue.Interface()
}

最佳答案

您可能希望使用反射来迭代结构的字段,获取每个字段的 validate 标记,并检查该字段。这意味着您必须在结构级别上进行验证。否则,如果您将类似 myInstance.OwnerID 的内容传递给函数,您将丢失与其关联的标签。

此代码循环遍历结构的字段并为每个字段获取 validate 标记:

func checkStruct(v interface{}) error {
    val := reflect.ValueOf(v)

    // Iterate through fields
    for i := 0; i < val.NumField(); i++ {
        // Lookup the validate tag
        field := val.Type().Field(i)
        tags := field.Tag
        validate, ok := tags.Lookup("validate")
        if !ok {
            // No validate tag.
            continue
        }

        // Get the value of the field.
        fieldValue := val.Field(i)

        // Validation logic here.
        fmt.Println("field", field.Name, "has validate tag", validate, "and value",
            fieldValue.Interface())
    }
    return nil
}

例如,我们可以将以下 CarModel 传递给它:

checkStruct(CarModel{
    OwnerID: 2,
    Type:    "B",
    A:       "http://google.com",
    B:       "192.168.1.1",
})

它会打印出以下内容:

field OwnerID has validate tag nonzero and value 2
field Type has validate tag regexp=(?)(A|B) and value B
field A has validate tag isurl and value http://google.com
field B has validate tag isip and value 192.168.1.1

关于validation - Golang 验证器多字段依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42390574/

有关validation - Golang 验证器多字段依赖的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  6. ruby-on-rails - 在 ruby​​ .gemspec 文件中,如何指定依赖项的多个版本? - 2

    我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这

  7. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  8. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  9. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  10. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

随机推荐