validator icon indicating copy to clipboard operation
validator copied to clipboard

What is the opposite of Required_If?

Open imraan-go opened this issue 4 years ago • 3 comments

  • [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.

imraan-go avatar Dec 02 '21 11:12 imraan-go

Is this package maintained anymore?

imraan-go avatar Dec 17 '21 10:12 imraan-go

@imraan-go yes it is maintained but I have very little free time to donate to it. I am trying to find additional maintainers.

deankarn avatar Dec 17 '21 18:12 deankarn

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())
		})
	}
}

steffen-petschow avatar Jan 06 '22 15:01 steffen-petschow