1

I am currently working on some homework for school and I am little stuck with my switch!

I am getting a response up until alert(card) in checkcard(); my problem is, none of the cases will actually validate the type of card that is is in reference too, I am not allowed to use any addons like jQuery etc etc. I'll post relevant code and be glad to hear from you guys :D I've commented the lines with #### for ease. Also, getcard does return correct card type as wished.

    function getCard(){
    var cardType = "unknown";
    var cardTypeArray = document.getElementById("chooseCard").getElementsByTagName("input");


    for(var i = 0; i < cardTypeArray.length; i++){
        if (cardTypeArray[i].checked) { 
            cardType = cardTypeArray[i].value;  
        }
    }
    alert ("cardtype is" + cardType);
    return cardType;

}
function checkCard(cardNumber){
    var errMsg = "";
    var card = getCard(); 
    //var cardNumber = document.getElementById("cardNumber").value;
    var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
    var regMaster = /^5[1-5][0-9]{14}$/;
    var regAmerica = /^3[47][0-9]{13}$/;
    alert(card); // works till here #######

    switch(card){
        case "Visa":
            if (parseInt(cardNumber.substring(0,1)!=4) {
                errMsg = "card number is not visa \n";
            }
            break;
        case "Mastercard":
            if (cardNumber.substring(0,1) !=5) {
                errMsg = "card number is not mastercard. \n";
            }
        break;
        case "AmericanExpress":
            if (cardNumber.substring(0,2) !=51) {
                errMsg = "card number not american express, \n";
            }
            break;


    }
    return errMsg;


}
function validator(){

    var errMsg = "";                                /* stores the error message */
    var result = true;  
    var visaCard = document.getElementById("visa").checked;
    var masterCard = document.getElementById("mastercard").checked;
    var americanExpress = document.getElementById("americanExpress").checked;
    var cardName = document.getElementById("cardName").value;
    //document.getElementById("cardName").setAttribute('maxlength',40);
    var regexAlpha = /^[a-zA-Z ]+$/;
    var cardNumber = document.getElementById("cardNumber").value;
    var regexNum =  /^[0-9]+$/;
    var date = new Date();
    var todayDateMonth = date.getMonth() + 1;
    var todayDateYear = date.getFullYear();
    var expMonth = document.getElementById("expMonth").value;
    var expYear = document.getElementById("expYear").value;
    var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
    var regMaster = /^5[1-5][0-9]{14}$/;
    var regAmerica = /^3[47][0-9]{13}$/;


    if (todayDateMonth > expMonth || todayDateYear > expYear){
        errMsg += "expiry date is wrong\n";
        result = false;
    }

    if (!(visaCard || masterCard || americanExpress)){
        errMsg += "please select visa, mastercard or american express\n";
        result = false;
    }   /* assumes no errors */


    if (cardNumber.length > 16 || cardNumber.length < 15 )
    {
        errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
        result = false;
    }else{
        checkCard(cardNumber); // Starts here #######

    }






    if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
    {
        errMsg = errMsg + "your card name must only contain alpha characters \n";
        result = false;
    }
    if (errMsg != "") {
        alert(errMsg);
    }
    return result;    //if false the information will not be sent to the server
}

function init() {
    if(document.getElementById("regform")!==null){
    var regForm = document.getElementById("regform");// get ref to the HTML element
    regForm.onsubmit = validate;    
    prefill_form();
}
    if(document.getElementById("bookform") !=null){
    var bookForm = document.getElementById("bookform");
    bookForm.onsubmit = validator;          /* assigns functions to corresponding events */
    var cancel = document.getElementById("cancelButton");
    cancel.onclick = cancelBooking;
    getBooking();

    }

}
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
  • Too much code. Please boil this down to a few dozen lines that reproduces your issue. –  Apr 22 '17 at 05:48
  • 2
    Could you make a jsfiddle for me and provide the HTML with it. I'll take a look at it. – Bram Apr 22 '17 at 05:48
  • Have you tried using the [debugger](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger)? If not, please do that and see how far you get. Then if you still have a question update your post to be a more **specific** question. – Sᴀᴍ Onᴇᴌᴀ Apr 22 '17 at 06:02
  • i'm new to this website, how do i upload my jsfiddle? and thankyou for prompt responses – Joseph Quaranta Apr 22 '17 at 06:08
  • tried using debugger, did not know whether i was using it wrong or it was just my code – Joseph Quaranta Apr 22 '17 at 06:09
  • Perhaps [this answer](http://stackoverflow.com/a/19623573/1575353) and/or the [SO documentation](http://stackoverflow.com/documentation/javascript/642/debugging#t=201704221832210679591) about JS debugging will be helpful ... – Sᴀᴍ Onᴇᴌᴀ Apr 22 '17 at 18:33

2 Answers2

2

okay so the problem was that i was not returning an error message or a false result. ill re post the same code as before but what i added to make it work for those interested. thank you for the feed back! i will be taking a few points on board. anyway code is below, look for ###################.

function validator(){

var errMsg = "";                                
var result = true;  


var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;

var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum =  /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expDate = document.getElementById("expDate").value;
var dateFormat = /^[\d]{2}\/[\d]{4}$/;





if (!dateFormat.test(expDate)){
    errMsg += "please select a valid date range\n";
    result = false;
}else if (todayDateYear > expDate.substring(3,7)){
    errMsg += "please select a valid expiry year\n";
    result = false;
} else if (todayDateYear == expDate.substring(3,7) && todayDateMonth > expDate.substring(0,2)){
    errMsg += "please select a valid expiry month\n";
    result = false;
}




if (!(visaCard || masterCard || americanExpress)){
    errMsg += "please select visa, mastercard or american express\n";
    result = false;
}   


if (cardNumber.length > 16 || cardNumber.length < 15 )
{
    errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
    result = false;
}else{
    // code below is what i added ######################################
    var tempMsg = checkCard(cardNumber);
    if (tempMsg != "") {
        errMsg = errMsg + tempMsg;
        result = false;
    };

} 







if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
    errMsg = errMsg + "your card name must only contain alpha characters \n";
    result = false;
}
if (errMsg != "") {
    alert(errMsg);
}
return result;    //if false the information will not be sent to the server

}

function checkCard(cardNumber){
var errMsg = "";
var card = getCard(); 
var cvv = document.getElementById("CVV").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
var cvvCheck3 =/^[0-9]{3}$/;
var cvvCheck4 =/^[0-9]{4}$/;




//do with if else 
switch(card){
    case "Visa":
        if (!regVisa.test(cardNumber) || !cvvCheck3.test(cvv)) {
            errMsg = "card number is not visa or cvv is wrrong \n";
        }
        break;
    case "Mastercard":
        if (!regMaster.test(cardNumber)  || !cvvCheck3.test(cvv)) {
            errMsg = "card number is not mastercard or cvv is wrong\n";
        }
    break;
    case "AmericanExpress":
        if (!regAmerica.test(cardNumber) || !cvvCheck4.test(cvv)) {
            errMsg = "card number not american express or cvv is wrong, \n";
        }
        break;
        default: 
        errMsg = "we cant process this card number \n";
}
return errMsg;  

}

1

The problem is with your code structure I see. You have an if condition inside of switch without any associated else. And without much knowledge of your test conditions I have good reason to believe you are not handling the cases and conditions properly. Simple way to find where your code went wrong is to put debugger; statement in your code. Have your developer tools open, you can do this by pressing F12 in most browsers or just from right click options. It should pause the execution of code there. Then there are two buttons you will see. 1. Play button which will resume code execution at once. 2. Kind of bent arrow, this is important one you can execute code line by line with this one and see which conditions were passed and which part of the code actually executed. Wanted to put this in comment but was too long to fit. If you have problems debugging feel free to comment here.And you can just google developer tools in case you can not open the particular window.

Prabhakar Poudel
  • 339
  • 7
  • 19
  • Your conditions inside cases looks fishy to me. You can verify the result in dev tools by typing the exact same code line by line and see if it matches your expectations. If it does proceed to next line. – Prabhakar Poudel Apr 22 '17 at 06:16
  • it is fishy because i want to be able to use the regex variables to check the card number not the substring. I tried to use !regVisa.test(cardNumber) instead but get an error saying that .test is not a function. yet it works down in the validator function. i will try the debugger and fish around with the code again and get back to everyone here. i appreciate this a lot, thankyou – Joseph Quaranta Apr 22 '17 at 06:29
  • I am sorry to say but your code is not clean at all. You have regular expressions defined in two function and not even used it once. This will cause you to have a lot of unwanted code in your program and make it difficult to debug. I would advice you to go through each line and decide if it can be done better? If it is required at all? if it is at the right place? If it is a logic, is it correct? Eventually you will get into habit of writing clean code. And will be easy to find bugs too. – Prabhakar Poudel Apr 22 '17 at 06:39