JavaScript: Check a credit card number format
JavaScript validation with regular expression: Exercise-2 with Solution
Validate Credit Card
Write a JavaScript program to check a credit card number.
Here are some format of some well-known credit cards.
- American Express :- Starting with 34 or 37, length 15 digits.
- Visa :- Starting with 4, length 13 or 16 digits.
- MasterCard :- Starting with 51 through 55, length 16 digits.
- Discover :- Starting with 6011, length 16 digits or starting with 5, length 15 digits.
- Diners Club :- Starting with 300 through 305, 36, or 38, length 14 digits.
- JCB :- Starting with 2131 or 1800, length 15 digits or starting with 35, length 16 digits.
Sample Solution:
JavaScript Code:
Output:
true false
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that implements the Luhn algorithm to validate a credit card number.
- Write a JavaScript function that strips non-digit characters from a credit card input and then validates its length and checksum.
- Write a JavaScript function that checks if a given credit card number starts with valid issuer digits (e.g., 4 for Visa) and passes the Luhn test.
- Write a JavaScript function that accepts a credit card number as a string, removes spaces/hyphens, and returns whether it is valid based on standard rules.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to test the first character of a string is uppercase or not.
Next: Write a pattern that matches e-mail addresses.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.