I'm trying to validate using JavaScript some form fields - so that if the Visa or Mastercard radio buttons are clicked - then the card number or expire date must also be filled in - what would be the recommended approach for this:

JavaScript code:

<script type="text/javascript">
 function paymentCheck(){
 if(document.form1.payment.Visa.checked == true) || (document.form1.payment.Mastercard.checked == true) && (document.form1.card.value == "") || (document.form1.exp.value="") {
    alert ("Please enter in a card or expiration number")

        return (true);

HTML code:

<FORM METHOD="post" ACTION="" name="form1">
<TR VALIGN="top">
        <TD ALIGN="right"><FONT SIZE=2><B>Payment Method:</B></FONT></TD>
        <TD ALIGN="left">
                <INPUT NAME="payment" TYPE="radio" VALUE="Visa">Visa<BR>
                <INPUT NAME="payment" TYPE="radio" VALUE="Mastercard">Mastercard<BR>
                <INPUT NAME="payment" TYPE="radio" VALUE="Check">Personal Check<BR>
<TR VALIGN=:top">
        <TD ALIGN="right"><FONT SIZE=2><B>Card Number/Expiration Date:</B></FONT></TD>
        <TD ALIGN="left"><INPUT NAME="card" SIZE=16>/<INPUT NAME="exp" SIZE=5></TD>
<TR VALIGN=:top">
        <TD ALIGN="right"><FONT SIZE=2><B>Card Code Number:</B></FONT></TD>
        <TD ALIGN="left"><INPUT NAME="cardcode" SIZE=5></TD>
    <TD ALIGN=RIGHT><INPUT TYPE="reset" VALUE="Reset"></TD>
    <TD ALIGN=LEFT><INPUT TYPE="submit" VALUE="Complete Order" onclick="paymentCheck()"></TD>
Re: JavaScript Validation of Radio Buttons and Form Fields 80 80
Member Avatar
Re: JavaScript Validation of Radio Buttons and Form Fields 80 80

Your card type does not have to be a user-input. It can be figured out from the number:

<script type="text/javascript">
function GetCardType(number)
    // visa
    var re = new RegExp("^4");
    if (number.match(re) != null)
        return "Visa";

    // Mastercard
    re = new RegExp("^5[1-5]");
    if (number.match(re) != null)
        return "Mastercard";

    // AMEX
    re = new RegExp("^3[47]");
    if (number.match(re) != null)
        return "AMEX";

    // Discover
    re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
    if (number.match(re) != null)
        return "Discover";

    // Diners
    re = new RegExp("^36");
    if (number.match(re) != null)
        return "Diners";

    // Diners - Carte Blanche
    re = new RegExp("^30[0-5]");
    if (number.match(re) != null)
        return "Diners - Carte Blanche";

    // JCB
    re = new RegExp("^35(2[89]|[3-8][0-9])");
    if (number.match(re) != null)
        return "JCB";

    // Visa Electron
    re = new RegExp("^(4026|417500|4508|4844|491(3|7))");
    if (number.match(re) != null)
        return "Visa Electron";

    return "";


Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.