I\'ve been trying to get this done but no success. I am using regular expression to validate the credit card number entered by user based on the type of credit card selected thr
You have 4 different if
blocks in your case, which hits every single block when the previous once fail.
Replace if
with if else
, that way if will only validate for a single use case.
Also you need not let the user know to be specific about the type of card that he is trying to enter. Just a single message to enter a valid number should suffice.
function ValidateCreditCardNumber() {
var ccNum = document.getElementById("cardNum").value;
var visaRegEx = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
var mastercardRegEx = /^(?:5[1-5][0-9]{14})$/;
var amexpRegEx = /^(?:3[47][0-9]{13})$/;
var discovRegEx = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;
var isValid = false;
if (visaRegEx.test(ccNum)) {
isValid = true;
} else if(mastercardRegEx.test(ccNum)) {
isValid = true;
} else if(amexpRegEx.test(ccNum)) {
isValid = true;
} else if(discovRegEx.test(ccNum)) {
isValid = true;
}
if(isValid) {
alert("Thank You!");
} else {
alert("Please provide a valid Visa number!");
}
}