github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/internal/builtin/builtin_bank_card.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  )
    12  
    13  // RuleBankCard implements `bank-card` rule:
    14  // Bank card number.
    15  //
    16  // Format: bank-card
    17  type RuleBankCard struct{}
    18  
    19  func init() {
    20  	Register(RuleBankCard{})
    21  }
    22  
    23  func (r RuleBankCard) Name() string {
    24  	return "bank-card"
    25  }
    26  
    27  func (r RuleBankCard) Message() string {
    28  	return "The {field} value `{value}` is not a valid bank card number"
    29  }
    30  
    31  func (r RuleBankCard) Run(in RunInput) error {
    32  	if r.checkLuHn(in.Value.String()) {
    33  		return nil
    34  	}
    35  	return errors.New(in.Message)
    36  }
    37  
    38  // checkLuHn checks `value` with LUHN algorithm.
    39  // It's usually used for bank card number validation.
    40  func (r RuleBankCard) checkLuHn(value string) bool {
    41  	var (
    42  		sum     = 0
    43  		nDigits = len(value)
    44  		parity  = nDigits % 2
    45  	)
    46  	for i := 0; i < nDigits; i++ {
    47  		var digit = int(value[i] - 48)
    48  		if i%2 == parity {
    49  			digit *= 2
    50  			if digit > 9 {
    51  				digit -= 9
    52  			}
    53  		}
    54  		sum += digit
    55  	}
    56  	return sum%10 == 0
    57  }