JavaScript: Check a credit card number format
JavaScript validation with regular expression: Exercise-2 with Solution
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:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript function to check whether a given value is a valid credit card or not</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function is_creditCard(str)
{
regexp = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;
if (regexp.test(str))
{
return true;
}
else
{
return false;
}
}
console.log(is_creditCard("378282246310006"));
console.log(is_creditCard("37828224630006"));
Sample Output:
true false
Flowchart:
Live Demo:
See the Pen javascript-regexp-exercise-2 by w3resource (@w3resource) on CodePen.
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.
JavaScript: Tips of the Day
How to insert an item into an array at a specific index (JavaScript)?
What you want is the splice function on the native array object.
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());
Ref: https://bit.ly/2BXbp04
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework