Home Web Front-end JS Tutorial Luhn algorithm for matching bank card numbers entered by users

Luhn algorithm for matching bank card numbers entered by users

Mar 29, 2018 pm 03:55 PM
enter bank card

This time I will bring you the Luhn algorithm that matches the bank card number entered by the user. What are the precautions for using the Luhn algorithm that matches the bank card number entered by the user. The following is a practical case, let's take a look.

During development, sometimes, in order to create a better user experience and reduce the pressure on the server side, it is necessary to perform format verification on some such as mobile phone numbers, bank card numbers, and ID numbers

The following is the code to determine whether the bank card number input is correct (format verification based on Luhn algorithm):

iOS code:

/**
 * 银行卡格式校验
 *
 * @param cardNo 银行卡号
 *
 * @return 
 */
+ (BOOL) checkCardNo:(NSString*) cardNo{
  
  
  int oddsum = 0;   //奇数求和
  int evensum = 0;  //偶数求和
  int allsum = 0;
  int cardNoLength = (int)[cardNo length];
  int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
  
  cardNo = [cardNo substringToIndex:cardNoLength - 1];
  for (int i = cardNoLength -1 ; i>=1;i--) {
    NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
    int tmpVal = [tmpString intValue];
    if (cardNoLength % 2 ==1 ) {
      if((i % 2) == 0){
        tmpVal *= 2;
        if(tmpVal>=10)
          tmpVal -= 9;
        evensum += tmpVal;
      }else{
        oddsum += tmpVal;
      }
    }else{
      if((i % 2) == 1){
        tmpVal *= 2;
        if(tmpVal>=10)
          tmpVal -= 9;
        evensum += tmpVal;
      }else{
        oddsum += tmpVal;
      }
    }
  }
  
  allsum = oddsum + evensum;
  allsum += lastNum;
  if((allsum % 10) == 0)
    return YES;
  else
    return NO;
}
Copy after login

Androd code:

/**
 
 * 匹配Luhn算法:可用于检测银行卡卡号
 
 * @param cardNo
 
 * @return
 
 */
 
public static boolean matchLuhn(String cardNo) {
 
  int[] cardNoArr = new int[cardNo.length()];
 
  for (int i=0; i<cardNo.length(); i++) {
 
    cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i)));
 
  }
 
  for(int i=cardNoArr.length-2;i>=0;i-=2) {
 
    cardNoArr[i] <<= 1;
 
    cardNoArr[i] = cardNoArr[i]/10 + cardNoArr[i]%10;
 
  }
 
  int sum = 0;
 
  for(int i=0;i<cardNoArr.length;i++) {
 
    sum += cardNoArr[i];
 
  }
 
  return sum % 10 == 0;
 
}
Copy after login

Attached (bank card number formatting):

Enter the bank card number During the process, we usually insert a "-" every 4 digits. A format similar to "1332-2131-2313-1231-212"
can be achieved by the following method:

Set the proxy of textField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  NSString *text = [textField text];
  NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
  string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
  if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
    return NO;
  }
  
  text = [text stringByReplacingCharactersInRange:range withString:string];
  text = [text stringByReplacingOccurrencesOfString:@"-" withString:@""];
  
  NSString *newString = @"";
  while (text.length > 0) {
    NSString *subString = [text substringToIndex:MIN(text.length, 4)];
    newString = [newString stringByAppendingString:subString];
    if (subString.length == 4) {
      newString = [newString stringByAppendingString:@"-"];
    }
    text = [text substringFromIndex:MIN(text.length, 4)];
  }
  
  newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
  
  if (newString.length >= 24) {
    return NO;
  }
  
  [textField setText:newString];
  
  return NO;
}
Copy after login

Finally, how to get the bank card number that does not contain the symbol "-"?

[self.textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""]

I believe you have mastered the method after reading the case in this article, and there will be more exciting things. Please pay attention to other related articles on php Chinese website!

Recommended reading:

How to implement the fuzzy matching function of regular expressions

Regular expressions to verify whether the QQ number is entered correct

The above is the detailed content of Luhn algorithm for matching bank card numbers entered by users. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Disabling Win11 Input Experience Guide Disabling Win11 Input Experience Guide Dec 27, 2023 am 11:07 AM

Recently, many Win11 users have encountered the problem that the input experience dialog box always flickers and cannot be turned off. This is actually caused by the default system services and components of Win11. We need to disable the relevant services first, and then disable the input experience service. Solved, let’s try it out together. How to turn off the input experience in win11: First step, right-click the start menu and open "Task Manager". Second step, find the three processes "CTF Loader", "MicrosoftIME" and "Service Host: Textinput Management Service" in order, right-click "End Task" "The third step, open the start menu, search and open "Services" at the top. The fourth step, find "Textinp" in it

Windows input encounters hang or high memory usage [Fix] Windows input encounters hang or high memory usage [Fix] Feb 19, 2024 pm 10:48 PM

The Windows input experience is a key system service responsible for processing user input from various human interface devices. It starts automatically at system startup and runs in the background. However, sometimes this service may automatically hang or occupy too much memory, resulting in reduced system performance. Therefore, it is crucial to monitor and manage this process in a timely manner to ensure system efficiency and stability. In this article, we will share how to fix issues where the Windows input experience hangs or causes high memory usage. The Windows Input Experience Service does not have a user interface, but it is closely related to handling basic system tasks and functions related to input devices. Its role is to help the Windows system understand every input entered by the user.

Can two WeChat accounts be bound to the same bank card? Can two WeChat accounts be bound to the same bank card? Aug 25, 2023 pm 03:13 PM

Two WeChat accounts cannot be bound to the same bank card. Bind a bank card to a WeChat account: 1. Open the WeChat application, click the "Me" option, and then select the "Pay" option; 2. Select the "Add Bank Card" option and enter the bank card information as prompted; 3. Once the bank card is successfully bound, users can use the bank card to make payments and transfers in WeChat.

Can someone else's bank card be bound to my WeChat account? Can someone else's bank card be bound to my WeChat account? Aug 25, 2023 am 10:03 AM

Other people's bank cards cannot be bound to your own WeChat. Steps to bind a bank card to WeChat: 1. Open the WeChat APP and enter the account number and password you need to log in for the first time; 2. Select "Me", then "Pay"; 3. Select "Wallet"; 4. Select "Bank Card" "; 5. Select "Add Bank Card"; 6. Enter the WeChat payment password; 7. Enter the bank card number to be bound, and then click "Next" to complete the bank card binding.

How to unbind bank card via WeChat How to unbind bank card via WeChat Apr 24, 2024 am 10:52 AM

1. Open the WeChat app, enter the [Me] page, select the [Service] menu, and click [Wallet]. 2. Select the [Bank Card] option, select the bank card to be unbound in the bank card interface, and enter its details page. 3. Finally, click the three-dot icon in the upper right corner, select [Unbind] and enter the payment password to complete the unbinding process.

How to unlink bank cards from Meituan How to unlink bank cards from Meituan Mar 27, 2024 pm 04:38 PM

1. Open the Meituan app, click [My] in the lower right corner, and click [Enter Wallet] on the right side of [Wallet]. 2. Select the [Bank Card] option, select and click the bank card that needs to be unbound, and enter the bank card interface. 3. Click [Bank Card Management], select [Unbind] in the pop-up window, and click [Still want to unbind]. 4. Enter the payment password on the identity verification interface, select [Reason for unbinding] or click [Skip] in the upper right corner.

How to unbind a bank card using WeChat How to unbind a bank card using WeChat Mar 29, 2024 pm 03:15 PM

1. Open the WeChat app, click [Me] in the lower right corner, select the [Service] option, and click [Wallet]. 2. Select the [Bank Card] option, select and click the bank card you want to unbind on the bank card interface, and enter the bank card details page. 3. Click the [three dots] icon in the upper right corner, select [Unbind], and enter the payment password to complete the unbinding operation.

How to unbind Alipay bank card How to unbind Alipay bank card Apr 26, 2024 am 10:19 AM

1. Open the Alipay app, enter the [My] page, select the [Bank Card] option, and click on the target bank card. 2. On the bank card interface, select [More Functions], enter [Help Center], check the reason for unbinding and click [Go to Unbind]. 3. Finally, select [Still want to unbind] and enter the payment password to complete the bank card unbinding.

See all articles