Hello Friends,
Validating Credit Card Numbers Using JavaScript
Some times we accept money through credits.We nee dto validate the credit cards ..
This task illustrates how to validate a credit card number by the following logic: • Check if the credit card number is empty; if it is, the field is not valid. • Remove any spaces. • Check the length of the credit card number; valid lengths are discussed in this task. If the length is wrong, the field is not valid. • Check for nonnumeric characters; if any occur, the field is not valid. • Otherwise, the field is valid.
function checkCreditCard(card) { if (card.length == 0) { window.alert(“You must provide a credit card number.”); return false; } card = card.replace(“ “,””); if (card.substring(0,1) == “4”) { if (card.length != 13 && card.length != 16) { window.alert(“Not enough digits in Visa number.”); return false; } } else if (card.substring(0,1) == “5” && (card.substring(1,2) >= “1” && card.substring(1,2) <= “5”)) { if (card.length != 16) { window.alert(“Not enough digits in MasterCard.”); return false; } } else if (card.substring(0,1) == “3” && (card.substring(1,2) == “4” || card.substring(1,2) == “7”)) { if (card.length != 15) { window.alert(“Not enough digits in American Expr.”); return false; } } else { window.alert(“This is not a valid card number.”); return false; } for (i=0; i{ if (card.charAt(i) < “0” || card.charAt(i) > “9”) { window.alert(“CCard must only contain numbers.”); return false; } } return true; }
Description: We nee dto call this method from onchange of textbox or onclick of submit button
For example:
<form name=”myForm” action=”target.html” onSubmit=”return checkForm(this);”> Credit Card: <input type=”text” name=”myField”><br> <input type=”submit”> </form>
Thanks & Regards, Datta.G.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|