Home > Web Front-end > JS Tutorial > JS uses regular rules to control user input and formatting of bank card numbers

JS uses regular rules to control user input and formatting of bank card numbers

巴扎黑
Release: 2017-06-16 11:08:36
Original
1782 people have browsed it

This article introduces to you through example code the method of using js to control the user's input of bank card number and formatting using regular expressions. The code is simple and easy to understand, very good, and has reference value. Friends who need it can refer to it

//js regular implementation of the control and formatting of bank card number input by users


<script language="javascript" type="text/javascript">
function formatBankNo (BankNo){
  if (BankNo.value == "") return;
  var account = new String (BankNo.value);
  account = account.substring(0,22); /*帐号的总数, 包括空格在内 */
  if (account.match (".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
    /* 对照格式 */
    if (account.match (".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|" + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|" +
    ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|" + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
      var accountNumeric = accountChar = "", i;
      for (i=0;i<account.length;i++){
        accountChar = account.substr (i,1);
        if (!isNaN (accountChar) && (accountChar != " ")) accountNumeric = accountNumeric + accountChar;
      }
      account = "";
      for (i=0;i<accountNumeric.length;i++){  /* 可将以下空格改为-,效果也不错 */
        if (i == 4) account = account + " "; /* 帐号第四位数后加空格 */
        if (i == 8) account = account + " "; /* 帐号第八位数后加空格 */
        if (i == 12) account = account + " ";/* 帐号第十二位后数后加空格 */
        account = account + accountNumeric.substr (i,1)
      }
    }
  }
  else
  {
    account = " " + account.substring (1,5) + " " + account.substring (6,10) + " " + account.substring (14,18) + "-" + account.substring(18,25);
  }
  if (account != BankNo.value) BankNo.value = account;
}
</script>
Copy after login


<input type="text" value="" size="25" onkeyup="formatBankNo(this)" onkeydown="formatBankNo(this)" name="account" id="account">
Copy after login

The above is the detailed content of JS uses regular rules to control user input and formatting of bank card numbers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template