govalidator
govalidator copied to clipboard
Parameterized Validator does not work for regular expressions
Validating struct using the tags does not work as expected for the parameterized validator. Parent Struct
package pmodels
// Notification represents a notification.
type Notification struct {
Recipients []Recipient `json:"recipients" valid:"required"`
From string `json:"from" valid:"required,email"`
Template *Template `json:"template" valid:"required"`
}
Child Struct
package pmodels
// Template represents a notification template.
type Template struct {
Name string `json:"name" valid:"required,alphanumeric"`
Data map[string]interface{} `json:"data"`
Language string `json:"language" valid:"required, matches([a-z]+-[A-Z]+)"`
}
I am trying to validate the "Language" using the parameterized validator provided in the documentation. But everytime I use it, the validation does not work as expected.
What I expect here is that, if the request JSON payload does not match the regex for language format then a validation error must be thrown. What I see rather is that the code bypasses it as "not a valid tag" and just moves ahead.
@avirkar,I have tested the latest version is ok, so which version did you find the problem on?
The test code is as follows:
func TestIssue343(t *testing.T) {
// Template represents a notification template.
type Template struct {
Name string `json:"name" valid:"required,alphanum"`
Data map[string] interface{} `json:"data"`
Language string `json:"language" valid:"required, matches([a-z]+-[A-Z]+)"`
}
// Notification represents a notification.
type Notification struct {
//Recipients []Recipient `json:"recipients" valid:"required"`
From string `json:"from" valid:"required,email"`
Template *Template `json:"template" valid:"required"`
}
mapInterface := make(map[string]interface{})
mapInterface["k1"] = 1
mapInterface["k2"] = "hello"
mapInterface["world"] = 1.05
temp := Template{
Name: "name123",
Data: mapInterface,
Language: "golangDDD",
}
result, err := ValidateStruct(Notification{
From: "[email protected]",
Template: &temp,
})
if err != nil {
println("error: " + err.Error())
}
println(result)
//output: error: Template.language: golangDDD does not validate as matches([a-z]+-[A-Z]+)
}
Hello guys! I forked this package cause owner disappeared. Hope, he will be back, but it would be easier to merge these changes back if he is back Link to my repo: create issue there and we'll discuss it.