jQuery Credit Card Validator

Last modified on January 10th, 2018 by Vincy.

In this tutorial, we are going to see, how to do credit card validation using jQuery. When the user submits his card details, then the jQuery code will be called to validate the data submitted by the user. We have already seen several of examples for validating user input submitted via the form

credit-card-validation

In this example, I have created a HMTL form containing input fields for entering the credit card details. I have used jQuery credit card validator plugin for validating credit card number. In this code, I have used Regex patterns to validate the fields Card Holder Name and the CVV. After validating the card details, the code will return the error message to the user if the invalid data is found.

View Demo

HTML Form with Credit Card Details

This HTML form contains input fields for the user to enter his credit card details. Those are Credit Card Number, Card Holder Name, Expiry Month / Year, CVV. On submitting this form, these fields are validated using a jQuery function.

<form id="frmContact" action="" method="post"
    onSubmit="return validate();">
    <div class="field-row">
        <label style="padding-top: 20px;">Card Holder Name</label> <span
            id="card-holder-name-info" class="info"></span><br /> <input
            type="text" id="card-holder-name" class="demoInputBox" />
    </div>
    <div class="field-row">
        <label>Card Number</label> <span id="card-number-info"
            class="info"></span><br /> <input type="text"
            id="card-number" class="demoInputBox">
    </div>
    <div class="field-row">
        <div class="contact-row column-right">
            <label>Expiry Month / Year</label> <span id="userEmail-info"
                class="info"></span><br /> <select name="expiryMonth"
                id="expiryMonth" class="demoSelectBox">
                <?php
                for ($i = date("m"); $i <= 12; $i ++) {
                    $monthValue = $i;
                    if (strlen($i) < 2) {
                        $monthValue = "0" . $monthValue;
                    }
                    ?>
                <option value="<?php echo $monthValue; ?>"><?php echo $i; ?></option>
                <?php
                }
                ?>
            </select> <select name="expiryMonth" id="expiryMonth"
                class="demoSelectBox">
                <?php
            for ($i = date("Y"); $i <= 2030; $i ++) {
                $yearValue = substr($i, 2);
                ?>
                <option value="<?php echo $yearValue; ?>"><?php echo $i; ?></option>
                <?php
            }
            ?>
            </select>
        </div>
        <div class="contact-row cvv-box">
            <label>CVV</label> <span id="cvv-info" class="info"></span><br />
            <input type="text" name="cvv" id="cvv"
                class="demoInputBox cvv-input">
        </div>
    </div>
    <div>
        <input type="submit" value="Submit" class="btnAction" />
    </div>
    <div id="error-message"></div>

</form>

jQuery Credit Card Validation

This jQuery script is used to validate the card details posted by the user via HTML form. In this script, I have invoked the credit card validated plugin function to validate the card number. Then, the other validations for checking mandatory fields and regex pattern matching are performed using jQuery. After validating the credit card details, the jQuery code will add the error message to the HTML if any invalid data is found.

<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="jquery-creditcardvalidator/jquery.creditCardValidator.js"></script>
<script>
	function validate() {
		var valid = true;
		$(".demoInputBox").css('background-color', '');
		var message = "";

		var cardHolderNameRegex = /^[a-z ,.'-]+$/i;
		var cvvRegex = /^[0-9]{3,3}$/;

		var cardHolderName = $("#card-holder-name").val();
		var cardNumber = $("#card-number").val();
		var cvv = $("#cvv").val();

		if (cardHolderName == "" || cardNumber == "" || cvv == "") {
			message += "<div>All Fields are Required.</div>";
			if (cardHolderName == "") {
				$("#card-holder-name").css('background-color', '#FFFFDF');
			}
			if (cardNumber == "") {
				$("#card-number").css('background-color', '#FFFFDF');
			}
			if (cvv == "") {
				$("#cvv").css('background-color', '#FFFFDF');
			}
			valid = false;
		}

		if (cardHolderName != "" && !cardHolderNameRegex.test(cardHolderName)) {
			message += "<div>Card Holder Name is Invalid</div>";
			$("#card-holder-name").css('background-color', '#FFFFDF');
			valid = false;
		}

		if (cardNumber != "") {
			$('#card-number').validateCreditCard(function(result) {
				if (!(result.valid)) {
					message += "<div>Card Number is Invalid</div>";
					$("#card-number").css('background-color', '#FFFFDF');
					valid = false;
				}
			});
		}

		else if (cvv != "" && !cvvRegex.test(cvv)) {
			message += "<div>CVV is Invalid</div>";
			$("#cvv").css('background-color', '#FFFFDF');
			valid = false;
		}

		if (message != "") {
			$("#error-message").show();
			$("#error-message").html(message);
		}
		return valid;
	}
</script>

jQuery Credit Card Validator – Output

This screenshot shows the output for the jQuery credit card validation.

jquery-credit-card-validation-output

View DemoDownload

This jQuery code tutorial was published on January 10, 2018.

↑ Back to Top

Share this Article