match.go raw

   1  // Copyright 2016 Qiang Xue. All rights reserved.
   2  // Use of this source code is governed by a MIT-style
   3  // license that can be found in the LICENSE file.
   4  
   5  package validation
   6  
   7  import (
   8  	"regexp"
   9  )
  10  
  11  // ErrMatchInvalid is the error that returns in case of invalid format.
  12  var ErrMatchInvalid = NewError("validation_match_invalid", "must be in a valid format")
  13  
  14  // Match returns a validation rule that checks if a value matches the specified regular expression.
  15  // This rule should only be used for validating strings and byte slices, or a validation error will be reported.
  16  // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
  17  func Match(re *regexp.Regexp) MatchRule {
  18  	return MatchRule{
  19  		re:  re,
  20  		err: ErrMatchInvalid,
  21  	}
  22  }
  23  
  24  // MatchRule is a validation rule that checks if a value matches the specified regular expression.
  25  type MatchRule struct {
  26  	re  *regexp.Regexp
  27  	err Error
  28  }
  29  
  30  // Validate checks if the given value is valid or not.
  31  func (r MatchRule) Validate(value interface{}) error {
  32  	value, isNil := Indirect(value)
  33  	if isNil {
  34  		return nil
  35  	}
  36  
  37  	isString, str, isBytes, bs := StringOrBytes(value)
  38  	if isString && (str == "" || r.re.MatchString(str)) {
  39  		return nil
  40  	} else if isBytes && (len(bs) == 0 || r.re.Match(bs)) {
  41  		return nil
  42  	}
  43  	return r.err
  44  }
  45  
  46  // Error sets the error message for the rule.
  47  func (r MatchRule) Error(message string) MatchRule {
  48  	r.err = r.err.SetMessage(message)
  49  	return r
  50  }
  51  
  52  // ErrorObject sets the error struct for the rule.
  53  func (r MatchRule) ErrorObject(err Error) MatchRule {
  54  	r.err = err
  55  	return r
  56  }
  57