required.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  var (
   8  	// ErrRequired is the error that returns when a value is required.
   9  	ErrRequired = NewError("validation_required", "cannot be blank")
  10  	// ErrNilOrNotEmpty is the error that returns when a value is not nil and is empty.
  11  	ErrNilOrNotEmpty = NewError("validation_nil_or_not_empty_required", "cannot be blank")
  12  )
  13  
  14  // Required is a validation rule that checks if a value is not empty.
  15  // A value is considered not empty if
  16  // - integer, float: not zero
  17  // - bool: true
  18  // - string, array, slice, map: len() > 0
  19  // - interface, pointer: not nil and the referenced value is not empty
  20  // - any other types
  21  var Required = RequiredRule{skipNil: false, condition: true}
  22  
  23  // NilOrNotEmpty checks if a value is a nil pointer or a value that is not empty.
  24  // NilOrNotEmpty differs from Required in that it treats a nil pointer as valid.
  25  var NilOrNotEmpty = RequiredRule{skipNil: true, condition: true}
  26  
  27  // RequiredRule is a rule that checks if a value is not empty.
  28  type RequiredRule struct {
  29  	condition bool
  30  	skipNil   bool
  31  	err       Error
  32  }
  33  
  34  // Validate checks if the given value is valid or not.
  35  func (r RequiredRule) Validate(value interface{}) error {
  36  	if r.condition {
  37  		value, isNil := Indirect(value)
  38  		if r.skipNil && !isNil && IsEmpty(value) || !r.skipNil && (isNil || IsEmpty(value)) {
  39  			if r.err != nil {
  40  				return r.err
  41  			}
  42  			if r.skipNil {
  43  				return ErrNilOrNotEmpty
  44  			}
  45  			return ErrRequired
  46  		}
  47  	}
  48  	return nil
  49  }
  50  
  51  // When sets the condition that determines if the validation should be performed.
  52  func (r RequiredRule) When(condition bool) RequiredRule {
  53  	r.condition = condition
  54  	return r
  55  }
  56  
  57  // Error sets the error message for the rule.
  58  func (r RequiredRule) Error(message string) RequiredRule {
  59  	if r.err == nil {
  60  		if r.skipNil {
  61  			r.err = ErrNilOrNotEmpty
  62  		} else {
  63  			r.err = ErrRequired
  64  		}
  65  	}
  66  	r.err = r.err.SetMessage(message)
  67  	return r
  68  }
  69  
  70  // ErrorObject sets the error struct for the rule.
  71  func (r RequiredRule) ErrorObject(err Error) RequiredRule {
  72  	r.err = err
  73  	return r
  74  }
  75