add min/max length validation, improve tests

This commit is contained in:
Aneurin Barker Snook
2023-10-07 10:43:21 +01:00
parent f41d6f248a
commit 923734fe25
4 changed files with 140 additions and 41 deletions
+32
View File
@@ -0,0 +1,32 @@
package validate
import (
"errors"
"fmt"
)
// MaxLength validates the length of a string as being less than or equal to a given maximum.
func MaxLength(l int) func(string) error {
return func(value string) error {
if len(value) > l {
if l != 1 {
return fmt.Errorf("Must not be longer than %d characters", l)
}
return errors.New("Must not be longer than 1 character")
}
return nil
}
}
// MinLength validates the length of a string as being greater than or equal to a given minimum.
func MinLength(l int) func(string) error {
return func(value string) error {
if len(value) < l {
if l != 1 {
return fmt.Errorf("Must not be shorter than %d characters", l)
}
return errors.New("Must not be shorter than 1 character")
}
return nil
}
}