21.6 C
New York

Javascript validates payment card number


Here is one simple way to validate payment card number using javascript.

Though while validating payment card number you may want to use javascript to allow only numbers on the client browser but how about telling javascript to check that the length of the digits entered is 16 digits the standard payment card number acceptable.

This below chunk of code is little but does all needful validation for a payment card number using javascript.

The below functions are used to achieve the validation as anticipated

  1. Javascript slice is used to maintain character length
  2. Javascript replace to maintain only numbers are taken
  3. javascript oninput event to prevent the user does not use copy and paste to inject / input invalid character javascript.
function validate(field) {
   let val = field.value;
   let data = val.replace(/[^0-9]/g, "");
   field.value = data.slice(0,16);
<label for="atmno">Payment card Number</label>
<input name="atmno" type="text" oninput="validate(this)">

this answer is available on stackoverflow https://stackoverflow.com/questions/51504819/javascript-to-only-allow-numbers-and-certain-length-and-no-periods But the answers there seems to be outdated and no longer working across different browser.

you can as well adjust data.slice(0,16) to data.slice(0,4) to validate payment card pin and cvv using same code above.

Owner and founder of shopinson.com. He is a passionate programmer with enthusiasm in daily discovering of solving logic with new block of codes. He loves creating contents and blogging his new discoveries on programming language and related peripherals.

Related articles


Recent articles