2017-07-06 48 views
0

在Golang ozzo驗證中,如何驗證依賴於另一個字段的字段?如何在golang中執行條件需求驗證?

舉例來說,如果我有以下幾點:

return validation.ValidateStruct(&c, 
     validation.Field(&c.Name, validation.Required, validation.Length(5, 20)), 

     validation.Field(&c.Gender, validation.In("Female", "Male")), 

     validation.Field(&c.Email, is.Email), 

     validation.Field(&c.Address), 

我如何添加一個驗證,只有當電子郵件不爲空的地址是必需的?

回答

1

可以實現它以兩種ways-

  • 基於前提價值即加上你自己的custom rules
  • 有條件加FieldRules檢查Email同時創造領域的規則,然後將其提供給validation.ValidateStruct

例如:

type Sample struct { 
    Name string 
    Gender string 
    Email string 
    Address Address 
} 

type Address struct { 
    // ... fields 
} 

func (s Sample) Validate() error { 
    var fieldRules []*validation.FieldRules 

    fieldRules = append(fieldRules, validation.Field(&s.Name, validation.Required, validation.Length(5, 20))) 
    fieldRules = append(fieldRules, validation.Field(&s.Gender, validation.In("Female", "Male"))) 
    fieldRules = append(fieldRules, validation.Field(&s.Email, is.Email)) 

    if len(strings.TrimSpace(s.Email)) > 0 { 
     fieldRules = append(fieldRules, validation.Field(&s.Address, validation.Required)) 
     fieldRules = append(fieldRules, validation.Field(&s.Address)) 
    } 

    return validation.ValidateStruct(&s, fieldRules...) 
} 
+0

我已經檢查過自定義規則部分。即使我編寫了一個自定義規則,我也需要將其與'xyz',validation.By(checkAbc)''代碼一起使用''。 – Crusaderpyro

+0

好的,你可以嘗試第二種方法嗎? – jeevatkm

+0

你能分享一些關於它應該如何工作的代碼嗎? – Crusaderpyro

相關問題