Permalink
Browse files

Added length validators

  • Loading branch information...
1 parent 5b0ded3 commit cc6f0f376fc40d40f58a913c1635378881c9b765 @thomaslee committed Mar 25, 2012
Showing with 68 additions and 1 deletion.
  1. +37 −0 gtfo.go
  2. +31 −1 gtfo_test.go
View
37 gtfo.go
@@ -73,6 +73,43 @@ func (req *requiredValidator) Validate(field *Field, value string) []ValidationE
return []ValidationError{}
}
+const (
+ useMinimum = 1 << iota
+ useMaximum = 2 << iota
+)
+
+type lengthValidator struct {
+ flags uint
+ minimum int
+ maximum int
+}
+
+func (l *lengthValidator) Validate(field *Field, value string) []ValidationError {
+ errors := []ValidationError{}
+ if (l.flags & useMinimum) == useMinimum {
+ if len(value) < l.minimum {
+ messageFormat := "%v must be at least %v characters long"
+ message := fmt.Sprintf(messageFormat, field.Name, l.minimum)
+ errors = append(errors, ValidationError{message: message})
+ }
+ } else if (l.flags & useMaximum) == useMaximum {
+ if len(value) > l.maximum {
+ messageFormat := "%v must be no more than %v characters long"
+ message := fmt.Sprintf(messageFormat, field.Name, l.maximum)
+ errors = append(errors, ValidationError{message: message})
+ }
+ }
+ return errors
+}
+
func Required() Validator {
return &required
}
+
+func MinLength(value int) Validator {
+ return &lengthValidator{flags: useMinimum, minimum: value}
+}
+
+func MaxLength(value int) Validator {
+ return &lengthValidator{flags: useMaximum, maximum: value}
+}
View
@@ -5,7 +5,7 @@ import "testing"
func TestSimpleForm(t *testing.T) {
form := &Form{}
form.Field("first_name", Required())
- params := map[string][]string{"first_name": []string{"Test"}}
+ params := map[string][]string{"first_name": {"Test"}}
errors := form.Validate(params)
if len(errors) > 0 {
t.Errorf("Did not expect validation errors!")
@@ -25,3 +25,33 @@ func TestAlternateDataFormat(t *testing.T) {
t.Errorf("Did not expect validation errors!")
}
}
+
+func TestLengthValidator(t *testing.T) {
+ form := &Form{}
+ form.Field("first_name", MinLength(2))
+ pass := []map[string]string{{"first_name": "Test"}, {"first_name": "Te"}}
+ fail := []map[string]string{{"first_name": "T"}}
+ checkFormWithInputs(t, form, pass, fail)
+
+ form = &Form{}
+ form.Field("age", MinLength(1), MaxLength(3))
+ pass = []map[string]string{{"age": "23"}, {"age": "100"}}
+ fail = []map[string]string{{"age": ""}, {"age": "1000"}}
+ checkFormWithInputs(t, form, pass, fail)
+}
+
+func checkFormWithInputs(t *testing.T, form *Form, pass, fail []map[string]string) {
+ for _, params := range pass {
+ errors := form.Validate(params)
+ if len(errors) > 0 {
+ t.Errorf("Expected no validation error for input %v", params)
+ }
+ }
+
+ for _, params := range fail {
+ errors := form.Validate(params)
+ if len(errors) == 0 {
+ t.Errorf("Expected validation error for input %v", params)
+ }
+ }
+}

0 comments on commit cc6f0f3

Please sign in to comment.