Skip to content

Commit c9d7d65

Browse files
Dean KarnDean Karn
authored andcommitted
Merge pull request #19 from joeybloggs/v3-development
issue-#18
2 parents 262159d + 622107d commit c9d7d65

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

doc.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,13 @@ Here is a list of the current built in validators:
150150
colors to be accepted. This can also be combined with 'and' for example
151151
( Usage: omitempty,rgb|rgba)
152152
153+
structonly
154+
When a field that is a nest struct in encountered and contains this flag
155+
any validation on the nested struct such as "required" will be run, but
156+
none of the nested struct fields will be validated. This is usefull if
157+
inside of you program you know the struct will be valid, but need to
158+
verify it has been assigned.
159+
153160
omitempty
154161
Allows conitional validation, for example if a field is not set with
155162
a value (Determined by the required validator) then other validation

validator.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const (
2222
orSeparator = "|"
2323
noValidationTag = "-"
2424
tagKeySeparator = "="
25+
structOnlyTag = "structonly"
2526
omitempty = "omitempty"
2627
validationFieldErrMsg = "Field validation for \"%s\" failed on the \"%s\" tag\n"
2728
validationStructErrMsg = "Struct:%s\n"
@@ -216,6 +217,10 @@ func (v *Validator) validateStructRecursive(top interface{}, s interface{}) *Str
216217

217218
} else {
218219

220+
if strings.Contains(tag, structOnlyTag) {
221+
continue
222+
}
223+
219224
if structErrors := v.validateStructRecursive(top, valueField.Interface()); structErrors != nil {
220225
validationErrors.StructErrors[typeField.Name] = structErrors
221226
// free up memory map no longer needed

validator_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,35 @@ func isEqualFunc(val interface{}, field interface{}, param string) bool {
137137
return val.(string) == field.(string)
138138
}
139139

140+
func (ms *MySuite) TestStructOnlyValidation(c *C) {
141+
142+
type Inner struct {
143+
Test string `validate:"len=5"`
144+
}
145+
146+
type Outer struct {
147+
InnerStruct *Inner `validate:"required,structonly"`
148+
}
149+
150+
outer := &Outer{
151+
InnerStruct: nil,
152+
}
153+
154+
errs := myValidator.ValidateStruct(outer).Flatten()
155+
c.Assert(errs, NotNil)
156+
157+
inner := &Inner{
158+
Test: "1234",
159+
}
160+
161+
outer = &Outer{
162+
InnerStruct: inner,
163+
}
164+
165+
errs = myValidator.ValidateStruct(outer).Flatten()
166+
c.Assert(errs, IsNil)
167+
}
168+
140169
func (ms *MySuite) TestGtField(c *C) {
141170

142171
type TimeTest struct {

0 commit comments

Comments
 (0)