. Credit Card Validation: You\'re starting your own credit card business. You\'v
ID: 3718032 • Letter: #
Question
.
Credit Card Validation:
You're starting your own credit card business. You've come up with a new way to validate
credit cards with a simple function called validateCreditCard that returns true or false.
Here are the rules for a valid number:
Number must be 16 digits, all of them must be numbers
You must have at least two different digits represented (all of the digits cannot be the same)
The final digit must be even
The sum of all the digits must be greater than 16
The following credit card numbers are valid:
9999-9999-8888-0000
6666-6666-6666-1666
The following credit card numbers are invalid:
a923-3211-9c01-1112 invalid characters
4444-4444-4444-4444 only one type of number
1111-1111-1111-1110 sum less than 16
6666-6666-6666-6661 odd final number
Write the above function java script in HTML code
Explanation / Answer
The below code validate whether the input credit card number is valid or invalid.
Coding:
<html>
<head><title>Validate Credit Card Number</title>
<script language="JavaScript" type="text/JavaScript">
function validateCreditCard(CardNumber)
{
if(validate(CardNumber))
{
document.getElementById("result").innerHTML="Valid Credit Card Number";
}
else
{
document.getElementById("result").innerHTML="Invalid Credit Card Number";
}
}
function validate(CardNumber)
{
var re = /^[0-9]+$/;
var lastnum = CardNumber.toString().charAt( CardNumber.length - 1 );
var sum=0,i,count=0;
for(i=0;i<CardNumber.length;i++)
{
sum=sum+parseInt(CardNumber.toString().charAt(i));
if(CardNumber.toString().charAt(0)==CardNumber.toString().charAt(i))
{
count++;
}
}
if(CardNumber.length!=16)/*This condition check the lenght of card number if less than 16 return false*/
{
return false;
}
else if(!re.test(CardNumber))/*This condition check the card number only has numeric value*/
{
return false;
}
else if((lastnum%2)!=0)/*this condition check the last digit of card number is even or odd if odd then retun false*/
{
return false;
}
else if(sum<=16)/*This condition check the sum of card number if less than 16 then return false*/
{
return false;
}
else if(count==CardNumber.length)/*This condition check the card number all are same if same then return false*/
{
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<div>
<table>
<tr><td>Enter the credit card number</td><td>:</td><td><input type="text" id="CardNumber"></td></tr>
<tr><td><input type="submit" value="Validate Credit Card Number"></td><td>:</td><td><label id="result"></label></td></tr>
</table>
</div>
</body>
</html>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.