string.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  type stringValidator func(string) bool
   8  
   9  // StringRule is a rule that checks a string variable using a specified stringValidator.
  10  type StringRule struct {
  11  	validate stringValidator
  12  	err      Error
  13  }
  14  
  15  // NewStringRule creates a new validation rule using a function that takes a string value and returns a bool.
  16  // The rule returned will use the function to check if a given string or byte slice is valid or not.
  17  // An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.
  18  func NewStringRule(validator stringValidator, message string) StringRule {
  19  	return StringRule{
  20  		validate: validator,
  21  		err:      NewError("", message),
  22  	}
  23  }
  24  
  25  // NewStringRuleWithError creates a new validation rule using a function that takes a string value and returns a bool.
  26  // The rule returned will use the function to check if a given string or byte slice is valid or not.
  27  // An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.
  28  func NewStringRuleWithError(validator stringValidator, err Error) StringRule {
  29  	return StringRule{
  30  		validate: validator,
  31  		err:      err,
  32  	}
  33  }
  34  
  35  // Error sets the error message for the rule.
  36  func (r StringRule) Error(message string) StringRule {
  37  	r.err = r.err.SetMessage(message)
  38  	return r
  39  }
  40  
  41  // ErrorObject sets the error struct for the rule.
  42  func (r StringRule) ErrorObject(err Error) StringRule {
  43  	r.err = err
  44  	return r
  45  }
  46  
  47  // Validate checks if the given value is valid or not.
  48  func (r StringRule) Validate(value interface{}) error {
  49  	value, isNil := Indirect(value)
  50  	if isNil || IsEmpty(value) {
  51  		return nil
  52  	}
  53  
  54  	str, err := EnsureString(value)
  55  	if err != nil {
  56  		return err
  57  	}
  58  
  59  	if r.validate(str) {
  60  		return nil
  61  	}
  62  
  63  	return r.err
  64  }
  65