forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/go-ozzo/ozzo-validation/match.go

74 lines
1.2 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
// Copyright 2016 Qiang Xue. All rights reserved.
2024-02-18 10:42:21 +00:00
// Use of this source code is governed by a MIT-style
2024-02-18 10:42:21 +00:00
// license that can be found in the LICENSE file.
package validation
import (
"errors"
"regexp"
)
// Match returns a validation rule that checks if a value matches the specified regular expression.
2024-02-18 10:42:21 +00:00
// This rule should only be used for validating strings and byte slices, or a validation error will be reported.
2024-02-18 10:42:21 +00:00
// An empty value is considered valid. Use the Required rule to make sure a value is not empty.
2024-02-18 10:42:21 +00:00
func Match(re *regexp.Regexp) *MatchRule {
2024-02-18 10:42:21 +00:00
return &MatchRule{
re: re,
2024-02-18 10:42:21 +00:00
message: "must be in a valid format",
}
2024-02-18 10:42:21 +00:00
}
type MatchRule struct {
re *regexp.Regexp
2024-02-18 10:42:21 +00:00
message string
}
// Validate checks if the given value is valid or not.
2024-02-18 10:42:21 +00:00
func (v *MatchRule) Validate(value interface{}) error {
2024-02-18 10:42:21 +00:00
value, isNil := Indirect(value)
2024-02-18 10:42:21 +00:00
if isNil {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
isString, str, isBytes, bs := StringOrBytes(value)
2024-02-18 10:42:21 +00:00
if isString && (str == "" || v.re.MatchString(str)) {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
} else if isBytes && (len(bs) == 0 || v.re.Match(bs)) {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return errors.New(v.message)
2024-02-18 10:42:21 +00:00
}
// Error sets the error message for the rule.
2024-02-18 10:42:21 +00:00
func (v *MatchRule) Error(message string) *MatchRule {
2024-02-18 10:42:21 +00:00
v.message = message
2024-02-18 10:42:21 +00:00
return v
2024-02-18 10:42:21 +00:00
}