【问题标题】:Grape: custom validator for each element of an arrayGrape:数组每个元素的自定义验证器
【发布时间】:2017-05-23 14:30:19
【问题描述】:

是否可以针对 Grape 中数组的每个元素运行自定义验证器?我知道我可以使用我的验证器来验证整个数组,但我认为如果我对每个元素都使用它会更好地显示错误消息。

我的参数如下所示:

  "conditions": [
      {
          "field": "interests",
          "operator": "any",
          "value": ['cars', 'cats']
      },
      {
          "field": "age",
          "operator": "gt",
          "value": 25
      }
  ]

使用requires :conditions, type: Array, valid_conditions: true,验证器会针对整个数组运行。我能得到最好的吗?

【问题讨论】:

    标签: ruby validation grape grape-api


    【解决方案1】:

    这是完全可能的,您可以在响应中声明特定键的值。

    assert_equal some_obj[0].first[1], "interests" 
    

    在 irb 中也是这样的

     ??  Success weeds out the uncommitted ~ irb
    2.2.3 :001 > a = [{:field=>"interests", :operator=>"any", :value=>["cars", "cats"]}]
     => [{:field=>"interests", :operator=>"any", :value=>["cars", "cats"]}]
    2.2.3 :002 > a[0].first
     => [:field, "interests"]
    2.2.3 :003 > a[0].first[1]
     => "interests"
    2.2.3 :004 >
    

    【讨论】:

      【解决方案2】:

      是的,这是可能的,但您必须使用自定义验证器。

      这是一个例子

      class Validator < Grape::Validations::Base
        def validate_param!(attr_name, params)
          unless params[attr_name].each { //your code here }
            fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: 'your message'
          end
        end
      end
      

      然后你会像这样使用它:

      requires :conditions, type: Array, validator: true
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-13
        • 1970-01-01
        • 2017-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多