Hi guys, I have written the following javascript code that validates the credit card information entered by a user. I now want to rewrite the same validation code in PHP. But since I am still very much new to PHP, can anyone give me pointers or help me rewrite it?
if (cardName=="") {
errMsg += "Please enter the name on the credit card.\n";
}
if ((!cardType==="MASTERCARD") || (!cardType==="VISA") || (!cardType==="AMERICANEXPRESS")) {
errMsg+="Please choose the credit card type.\n";
}
else {
if (cardType==="VISA") {
if (!cardNumber.match(/^4\d+/)) {
errMsg+="Please enter a valid card number.\n";
result = false;
}
}
if (cardType==="MASTERCARD") {
if (!cardNumber.match(/^5[1-5][0-9]{14}$/)){
errMsg+="Please enter a valid card number.\n";
result = false;
}
}
if (cardType==="AMERICANEXPRESS") {
if (!cardNumber.match(/^3[4-7][0-9]{13}$/)) {
errMsg+="Please enter a valid card number.\n";
result = false;
}
}
}
if ((cardType==="MASTERCARD") || (cardType==="VISA")) {
if (!cvv.match(/^[1-9]{3}$/)) {
errMsg+="Please enter a valid cvv.\n";
result = false;
}
}
else if (cardType==="AMERICANEXPRESS") {
if (!cvv.match(/^[1-9]{4}$/)) {
errMsg+="Please enter a valid cvv.\n";
result = false;
}
}
if (cardNumber=="") {
errMsg += "Please enter the credit card number. \n";
}
if (cardDate=="") {
errMsg+="Please enter the credit card expiration date. \n";
}
else {
if (!cardDate.match(/^(0[1-9]|1[0-2])[-][0-9]{2}/)) {
errMsg += "The expire date format is not correct!\n";
result = false;
}
else {
// get current year and month reference: https://stackoverflow.com/questions/32931526/how-to-use-javascript-to-validate-credit-card-expire-datemm-yy-must-not-expire
var d = new Date();
var currentYear = d.getFullYear();
var currentMonth = d.getMonth() + 1;
// get parts of the expiration date
var parts = cardDate.split('-');
var year = parseInt(parts[1], 10) + 2000;
var month = parseInt(parts[0], 10);
// compare the dates
if (year < currentYear || (year == currentYear && month < currentMonth)) {
errMsg += "The expiry date has passed.\n";
result = false;
}
}
if (cvv=="") {
errMsg+="Please enter the CCV code. \n";
// more validation here
}
if (errMsg!="") {
alert (errMsg);
}
}
return result;