60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package options
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
type StringCharacterRange struct {
|
|
Min rune
|
|
Max rune
|
|
}
|
|
|
|
func (crange *StringCharacterRange) Validate(value rune) bool {
|
|
return value >= crange.Min && value <= crange.Max
|
|
}
|
|
|
|
type StringTranscoderOption struct {
|
|
DefaultValue string
|
|
Required bool
|
|
MaxLength int
|
|
MinLength int
|
|
AllowedCharacterRanges []StringCharacterRange
|
|
}
|
|
|
|
func (option *StringTranscoderOption) IsRequired() bool {
|
|
return option.Required
|
|
}
|
|
|
|
func (option *StringTranscoderOption) Validate(value interface{}) (err error) {
|
|
stringValue, ok := value.(string)
|
|
if !ok {
|
|
err = errors.New("value is not a string")
|
|
return
|
|
}
|
|
|
|
if option.MaxLength > 0 && len(stringValue) > option.MaxLength {
|
|
err = errors.New("text is too long")
|
|
return
|
|
}
|
|
|
|
if len(stringValue) < option.MinLength {
|
|
err = errors.New("text is too short")
|
|
return
|
|
}
|
|
|
|
if option.AllowedCharacterRanges != nil {
|
|
for index, character := range stringValue {
|
|
for _, crange := range option.AllowedCharacterRanges {
|
|
if !crange.Validate(character) {
|
|
err = fmt.Errorf("character \"%c\" at position %d is outside of valid character range", character, index)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
err = nil
|
|
return
|
|
}
|