absent.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  	// ErrNil is the error that returns when a value is not nil.
   9  	ErrNil = NewError("validation_nil", "must be blank")
  10  	// ErrEmpty is the error that returns when a not nil value is not empty.
  11  	ErrEmpty = NewError("validation_empty", "must be blank")
  12  )
  13  
  14  // Nil is a validation rule that checks if a value is nil.
  15  // It is the opposite of NotNil rule
  16  var Nil = absentRule{condition: true, skipNil: false}
  17  
  18  // Empty checks if a not nil value is empty.
  19  var Empty = absentRule{condition: true, skipNil: true}
  20  
  21  type absentRule struct {
  22  	condition bool
  23  	err       Error
  24  	skipNil   bool
  25  }
  26  
  27  // Validate checks if the given value is valid or not.
  28  func (r absentRule) Validate(value interface{}) error {
  29  	if r.condition {
  30  		value, isNil := Indirect(value)
  31  		if !r.skipNil && !isNil || r.skipNil && !isNil && !IsEmpty(value) {
  32  			if r.err != nil {
  33  				return r.err
  34  			}
  35  			if r.skipNil {
  36  				return ErrEmpty
  37  			}
  38  			return ErrNil
  39  		}
  40  	}
  41  	return nil
  42  }
  43  
  44  // When sets the condition that determines if the validation should be performed.
  45  func (r absentRule) When(condition bool) absentRule {
  46  	r.condition = condition
  47  	return r
  48  }
  49  
  50  // Error sets the error message for the rule.
  51  func (r absentRule) Error(message string) absentRule {
  52  	if r.err == nil {
  53  		if r.skipNil {
  54  			r.err = ErrEmpty
  55  		} else {
  56  			r.err = ErrNil
  57  		}
  58  	}
  59  	r.err = r.err.SetMessage(message)
  60  	return r
  61  }
  62  
  63  // ErrorObject sets the error struct for the rule.
  64  func (r absentRule) ErrorObject(err Error) absentRule {
  65  	r.err = err
  66  	return r
  67  }
  68