github.com/gogf/gf@v1.16.9/util/gvalid/gvalid_validator_rule_luhn.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/gogf/gf.
     6  
     7  package gvalid
     8  
     9  // checkLuHn checks `value` with LUHN algorithm.
    10  // It's usually used for bank card number validation.
    11  func (v *Validator) checkLuHn(value string) bool {
    12  	var (
    13  		sum     = 0
    14  		nDigits = len(value)
    15  		parity  = nDigits % 2
    16  	)
    17  	for i := 0; i < nDigits; i++ {
    18  		var digit = int(value[i] - 48)
    19  		if i%2 == parity {
    20  			digit *= 2
    21  			if digit > 9 {
    22  				digit -= 9
    23  			}
    24  		}
    25  		sum += digit
    26  	}
    27  	return sum%10 == 0
    28  }