简体   繁体   中英

how to validate credit cards using jquery.validation creditcard2?

I was hoping someone can point me in the right direction. I am looking to use this plugin along with jquery.validation plugin in my forms but from what I see I would need to use a select tag in order for creditcard2 to function correctly.

What I currently have is this:

 <p class="ccType">
     <label for="card_type" class="error">You must select a credit card from one of the following.</label>
        <br>
     <input type="radio" value="1000" id="card_type_1000" name="card_type" style="outline:none; border:none;" /> 
        <img src="../visa.png" alt="Visa" width="50" height="30" align="top" /> 
        <input type="radio" value="1002" id="card_type_1002" name="card_type" style="outline:none; border:none;" /> 
        <img src="../mastercard.png" alt="Mastercard" width="50" height="30" align="top" /> 
        <input type="radio" value="1006" id="card_type_1006" name="card_type" style="outline:none; border:none;" /> 
        <img src="../discover.png" alt="Discover" width="50" height="30" align="top" /> 
        <input type="radio" value="1004" id="card_type_1004" name="card_type" style="outline:none; border:none;" /> 
        <img src="../amex.png" alt="American Express" width="50" height="30" align="top" />
    </p>

value = 1000 is "Visa"

value = 1002 is "MasterCard"

value = 1006 is "Discover"

value = 1004 is "AmEx"

The plugin site mentions creating a lookup hash. I don't know how to create one. Also the documentation that is on the site only shows examples using <select></select> . I am using inputs.

How can I get this to work with the set up that I currently have.

any suggestions?

A lookup hash would look like

var hash = {
    1000: "Visa",
    1002: "MasterCard",
    1004: "AmEx",
    1006: "Discover"
};

Then you could use the following validation function, of course built into your current setup:

$("#myform").validate({
    rules: {
        cardnum: { // this should be the id of the card number field
            creditcard2: function(){ return hash[$('.ccType > input:checked').val()]; }
        }
    }       
});

This rather concise code first looks for all the inputs in your .ccType element. Then it selects the one that is checked (if any) and gets its value. Then the value is pushed through the hash to change it to a value the plugin likes. And... let's hope this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM