validator
validator copied to clipboard
What is the opposite of Required_If?
- [x] I have looked at the documentation here first? yes
- [x] I have looked at the examples provided that may showcase my question here? yes
Package version eg. v9, v10:
v10
Issue, Question or Enhancement:
https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Required_If
Code sample, to showcase or reproduce:
type Experience struct {
Id int
JobTypeId int
Type int
}
Now I want, JobTypeId to be present only if Type ==1. For any other value JobTypeId should not be set. Is there something like this must_not_required_if=Field1 is not foobar or should_exists_only_if=Field foobar (otherwise validation should fail.
Is this package maintained anymore?
@imraan-go yes it is maintained but I have very little free time to donate to it. I am trying to find additional maintainers.
package foo_test
import (
"fmt"
"testing"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/require"
)
type Experience struct {
Id int
JobTypeId int `validate:"required_if=Type 1"`
Type int
}
func TestJobTypeIdIsPresentIfTypeIs1(t *testing.T) {
v := validator.New()
tests := []struct {
Experience Experience
validationErrStr string
}{
{Experience: Experience{JobTypeId: 0, Type: 1},
validationErrStr: "Key: 'Experience.JobTypeId' Error:Field validation for 'JobTypeId' failed on the 'required_if' tag",
},
{Experience: Experience{JobTypeId: 3, Type: 1}, validationErrStr: ""},
{Experience: Experience{JobTypeId: 0, Type: 0}, validationErrStr: ""},
{Experience: Experience{JobTypeId: 0, Type: 2}, validationErrStr: ""},
{Experience: Experience{JobTypeId: 1, Type: 2}, validationErrStr: ""},
}
for _, tc := range tests {
testName := fmt.Sprintf("test with JobTypeId: %d, Type: %d", tc.Experience.JobTypeId, tc.Experience.Type)
t.Run(testName, func(t *testing.T) {
err := v.Struct(tc.Experience)
if tc.validationErrStr == "" {
require.NoError(t, err)
return
}
require.Error(t, err)
require.Equal(t, tc.validationErrStr, err.Error())
})
}
}