-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.go
More file actions
35 lines (28 loc) · 760 Bytes
/
Copy pathschema.go
File metadata and controls
35 lines (28 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package gv
import gverrors "github.com/501urchin/gv/internal/errors"
type schemaFunc[T any] func(d *T) error
type schemaValidator[T any] struct {
fn schemaFunc[T]
}
/*
Schema lets you define reusable validation logic.
Example:
schema := Schema(func(info *T) error {
return First(
String(info.Field1).Required().Min(3).Max(25).Validate(),
String(info.Field2).Required().NoWhitespace().Validate(),
)
})
*/
func Schema[T any](fn schemaFunc[T]) *schemaValidator[T] {
return &schemaValidator[T]{fn: fn}
}
// Validate method runs the validation schema on the data pointer
//
// err := schema.Validate(dataPointer)
func (s *schemaValidator[T]) Validate(data *T) error {
if data == nil {
return gverrors.ErrIsNilOrEmpty
}
return s.fn(data)
}