Giter VIP home page Giter VIP logo

jquery.payment's Introduction

jQuery.payment Build Status

A general purpose library for building credit card forms, validating inputs and formatting numbers.

Project status

jquery.payment is deprecated. We recommend that you use either Stripe Checkout or Stripe Elements to collect card information.

We will patch jquery.payment for major critical/security issues, but we won't be adding new features.

Usage

You can make an input act like a credit card field (with number formatting and length restriction):

$('input.cc-num').payment('formatCardNumber');

Then, when the payment form is submitted, you can validate the card number on the client-side:

var valid = $.payment.validateCardNumber($('input.cc-num').val());

if (!valid) {
  alert('Your card is not valid!');
  return false;
}

You can find a full demo here.

Supported card types are:

  • Visa
  • MasterCard
  • American Express
  • Diners Club
  • Discover
  • UnionPay
  • JCB
  • Maestro
  • Forbrugsforeningen
  • Dankort

(Additional card types are supported by extending the $.payment.cards array.)

API

$.fn.payment('formatCardNumber')

Formats card numbers:

  • Includes a space between every 4 digits
  • Restricts input to numbers
  • Limits to 16 numbers
  • Supports American Express formatting
  • Adds a class of the card type (e.g. 'visa') to the input

Example:

$('input.cc-num').payment('formatCardNumber');

$.fn.payment('formatCardExpiry')

Formats card expiry:

  • Includes a / between the month and year
  • Restricts input to numbers
  • Restricts length

Example:

$('input.cc-exp').payment('formatCardExpiry');

$.fn.payment('formatCardCVC')

Formats card CVC:

  • Restricts length to 4 numbers
  • Restricts input to numbers

Example:

$('input.cc-cvc').payment('formatCardCVC');

$.fn.payment('restrictNumeric')

General numeric input restriction.

Example:

$('[data-numeric]').payment('restrictNumeric');

$.payment.validateCardNumber(number)

Validates a card number:

  • Validates numbers
  • Validates Luhn algorithm
  • Validates length

Example:

$.payment.validateCardNumber('4242 4242 4242 4242'); //=> true

$.payment.validateCardExpiry(month, year)

Validates a card expiry:

  • Validates numbers
  • Validates in the future
  • Supports year shorthand

Example:

$.payment.validateCardExpiry('05', '20'); //=> true
$.payment.validateCardExpiry('05', '2015'); //=> true
$.payment.validateCardExpiry('05', '05'); //=> false

$.payment.validateCardCVC(cvc, type)

Validates a card CVC:

  • Validates number
  • Validates length to 4

Example:

$.payment.validateCardCVC('123'); //=> true
$.payment.validateCardCVC('123', 'amex'); //=> true
$.payment.validateCardCVC('1234', 'amex'); //=> true
$.payment.validateCardCVC('12344'); //=> false

$.payment.cardType(number)

Returns a card type. Either:

  • visa
  • mastercard
  • amex
  • dinersclub
  • discover
  • unionpay
  • jcb
  • maestro
  • forbrugsforeningen
  • dankort

The function will return null if the card type can't be determined.

Example:

$.payment.cardType('4242 4242 4242 4242'); //=> 'visa'

$.payment.cardExpiryVal(string) and $.fn.payment('cardExpiryVal')

Parses a credit card expiry in the form of MM/YYYY, returning an object containing the month and year. Shorthand years, such as 13 are also supported (and converted into the longhand, e.g. 2013).

$.payment.cardExpiryVal('03 / 2025'); //=> {month: 3, year: 2025}
$.payment.cardExpiryVal('05 / 04'); //=> {month: 5, year: 2004}
$('input.cc-exp').payment('cardExpiryVal') //=> {month: 4, year: 2020}

This function doesn't perform any validation of the month or year; use $.payment.validateCardExpiry(month, year) for that.

$.payment.cards

Array of objects that describe valid card types. Each object should contain the following fields:

{
  // Card type, as returned by $.payment.cardType.
  type: 'mastercard',
  // Array of prefixes used to identify the card type.
  patterns: [
      51, 52, 53, 54, 55,
      22, 23, 24, 25, 26, 27
  ],
  // Array of valid card number lengths.
  length: [16],
  // Array of valid card CVC lengths.
  cvcLength: [3],
  // Boolean indicating whether a valid card number should satisfy the Luhn check.
  luhn: true,
  // Regex used to format the card number. Each match is joined with a space.
  format: /(\d{1,4})/g
}

When identifying a card type, the array is traversed in order until the card number matches a prefix in patterns. For this reason, patterns with higher specificity should appear towards the beginning of the array.

Example

Look in ./example/index.html

Building

Run cake build

Running tests

Run cake test

Autocomplete recommendations

We recommend you turn autocomplete on for credit card forms, except for the CVC field (which should never be stored). You can do this by setting the autocomplete attribute:

<form autocomplete="on">
  <input class="cc-number" autocomplete="cc-number">
  <input class="cc-exp" autocomplete="cc-exp">
  <input class="cc-cvc" autocomplete="off">
</form>

You should mark up your fields using the Autofill spec. These are respected by a number of browsers, including Chrome, Safari, Firefox.

Mobile recommendations

We recommend you to use <input type="tel"> which will cause the numeric keyboard to be displayed on mobile devices:

<input type="tel" class="cc-number">

jquery.payment's People

Contributors

ajlai avatar alex-stripe avatar bdukes avatar buzzedword avatar byroot avatar christianblais avatar coliff avatar daniel-stripe avatar davidcornu avatar dwilkie avatar esaborit4code avatar fishrock123 avatar gsamokovarov avatar hashnuke avatar iokill avatar jamesreggio avatar jenan-stripe avatar jenanwise avatar kennethormandy avatar kulte avatar kyleconroy avatar maccman avatar matt-stripe avatar mduvall avatar michaelvillar avatar narkeeso avatar rmm5t avatar rovermicrover avatar slexaxton avatar tyrantkhan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.payment's Issues

Demo is not properly handling American Express CVV/Card Numbers

In the demo http://stripe.github.com/jquery.payment/example/

I tried with my credit card number (amex), valid expiration date, and a 3-digit CVV. The validation passed even though amex CVV should be 4 digits.

I also tried with a few other numbers from http://www.getcreditcardnumbers.com/

If you want a concrete test case:

Card Number 378282246310005 <-- this is the test case that paypal recommends: https://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
Expiration 12 / 21
CVV 123

Question: why disable autocomplete for CVC?

On README.md:

We recommend you turn autocomplete on for credit card forms, except for the CVC field.

Why do you recommend this? It'd be nice if the README had an explanation for it.

Also, at first glance it seems to conflict with one of the following paragraphs:

Set autocompletetype to (...) cc-csc for the CVC (security code).

How to select valid credidt card?

Any one know how to use something like that if you have for example visa your card is selected

js

$("#card-holder").payment(function(e) {
if (e.cardType == null) {
$(".cards li").removeClass("off");

    }
    else{
    $(".cards li").addClass("off");
    $(".cards ." + e.cardType.name).removeClass("off");
    }
});

html

  • Visa
  • MasterCard
  • Maestro

css

ul.cards {
overflow: hidden;
height: 30px;
margin-bottom: 0;
padding-bottom: 0;
padding-top: 10px;
list-style: none;
}

.cards li {
-webkit-transition: all .2s;
-moz-transition: all .2s;
-ms-transition: all .2s;
-o-transition: all .2s;
transition: all .2s;
background: url(../img/card_logos.png) 0 0;
float: left;
height: 32px;
margin-right: 8px;
text-indent: -9999px;
width: 51px;
list-style: none;
}

.cards li:last-child {
margin-right: 0
}

.cards .visa_electron {
background-position: 204px 0
}

.cards .mastercard {
background-position: 153px 0
}

.cards .maestro {
background-position: 102px 0
}

.cards .discover {
background-position: 51px 0
}

.cards .visa.off {
background-position: 0 32px
}

.cards .visa_electron.off {
background-position: 204px 32px
}

.cards .mastercard.off {
background-position: 153px 32px
}

.cards .maestro.off {
background-position: 102px 32px
}

.cards .discover.off {
background-position: 51px 32px
}

Mismatch between formatCardExpiry and validateCardExpiry

If you verify this date "11/20131" with validateCardExpiry it will be valid, but it will be not valid with formatCardExpiry.

This case it can be tested if you paste that date into the field instead of type it in.

validateCardExpiry: validate just that the year should be after the current time, it will allow a year bigger than 4 digits.

formatCardExpiry: validate that the date should be a number not bigger than 4 digits.

Treat space like / in expiry formatting

Try the expiry formatting at:
http://stripe.github.io/jquery.payment/example/

If you type "1" -> "/" -> "1" -> "4"
You properly end up with 01 / 14

However if you instead use a space โ€“ which imho is a reasonable possibility as it too indicates a separation of the two digits โ€“ you end up with "11 / 4" because the space is simply eaten.

Maybe I should do a separate bug for it, but capturing tab would also be a good idea.
Specifically capturing tab in the one circumstance:
"1" "1" "4"
Where takes place of / or space.

jQuery.Payment fails to init when loaded via CDN

Hi,
For some reason, I cannot get the jquery.payment library to initialize when loaded via a CDN. The source seems to load fine, but I cannot perform the provided functions of the library like I can if I load the script locally. Locally loading the script works just fine.

I tried this with the version of jquery.payment hosted on cdnjs.com AND jsdelivr.com. It has the same problem at both locations.

Example (view console error when run/loaded):
http://jsfiddle.net/DDw6A/
http://jsfiddle.net/j4ARK/

Any idea what is causing this?

Feature Request: Clean value function

The input masking for the card number is great, but a function to return the unformatted number would be very helpful for back-end processing that doesn't want spaces or dashes.

Amex CVC validation passes with only 3 digits

It's my understanding that the CVC on the front of an American Express card (amex) is always, and must be, 4 digits - or validation server side will fail.

However, the following happens when applying validation to the CVC field;

$.payment.validateCardCVC('123', 'amex'); //=> true
$.payment.validateCardCVC('1234', 'amex'); //=> true

Shouldn't entering only 3 digits for type 'amex' return false?

restrictCVC limits to 5 characters, not 4

The README states:

Restricts length to 4 numbers

However, the code is this:

  restrictCVC = function(e) {
    var $target, val;
    $target = $(e.currentTarget);
    val = $target.val();
    return val.length <= 4;
  };

Which is triggered by this code:

$.fn.formatCardCVC = function() {
    this.restrictNumeric();
    return this.on('keypress', restrictCVC);
  };

When you press a key to enter the 5th digit, the restrictCVC method will return true, thereby allowing a 5th digit to be entered.

I think this line:

   return val.length <= 4;

Should be changed to this:

   return val.length < 4;

Visa card detection issue

I similar to the JCB issue just opened this one for visa:

4012888818888 - appears to be a valid visa card, but unaccepted by

$.payment.validateCardNumber("4012888818888")

Perhaps, I have something mixed up are these actually invalid numbers but valid for a test environment?

Let me know if there is more information I can provide...

JCB card type issue

I have the following test card for JCB and this is indicating it's an invalid card type

the test number is:

JCB: 3088000000000017

$.payment.cardType("3088000000000017") -> null

Month validation

Can anyone help me with this why is always giving me false

   $.payment.validateCardMonthExpiry = function(month) {
   var currentTime, expiry, _ref;

    if (typeof month === 'object' && 'month' in month) {
        _ref = month, month = _ref.month;
    }
    if (!month) {
        return false;
    }
    month = $.trim(month);

    if (!/^\d+$/.test(month)) {
        return false;
    }
    if (!(parseInt(month, 10) <= 12)) {
        return false;
    }
   expiry = new Date(month);
   currentTime = new Date;
   expiry.setMonth(expiry.getMonth() - 1);
   expiry.setMonth(expiry.getMonth() + 1, 1);
   return expiry > currentTime;

};

and when i validate this like that

if (!$.payment.validateCardMonthExpiry($('#month-holder').val())) {
        $('#month-error').fadeIn('slow');

    } else {
        $('#month-error').fadeOut('slow');
    }

How to validate month and years as separate fields

What is should do if month and year is spearate field i already have

$.payment.fn.formatMonthExpiry = function() {
this.payment('restrictNumeric');
this.on('keypress', restrictMonthExpiry);
this.on('keypress', formatMonthExpiry);
return this;
};

$.payment.fn.formatTwoDigitYearExpiry = function() {
    this.payment('restrictNumeric');
    this.on('keypress', restrictTwoDigitYearExpiry);
    this.on('keypress', formatYearExpiry);
    return this;
};

$.payment.fn.formatFourDigitYearExpiry = function() {
    this.payment('restrictNumeric');
    this.on('keypress', restrictFourDigitYearExpiry);
    this.on('keypress', formatYearExpiry);
    return this;
};

can anyone know how to do it

Visa card starting with 0434

I have a customer from Hong Kong who claims that she has a Visa card issued by HSBC in Hong Kong that starts with 0434. The validation fails for this card number (validateCardNumber) because jquery.payment is unable to recognise card type for this number. From what I know Visa card numbers start with 4 so I asked the client to double check whether her card number indeed starts with 0434 and she confirmed this.

Has anyone come across such Visa card numbers (starting with 0 or 0434)?

Expiry field should handle delete and / as if / wasn't auto inserted

Typing 0413 should be the same as typing 01Del413

Currently it results in "01 / 413" in the input due to the Del deleting the "/"

Edit: It should also handle automatic leading zero insertion:
1/Del2/13 => "12 / 13" not "01 / 213". When you get to "01 / 2|" and hit / it should remove the leading zero and push the 2 into the month resulting in "12 / |"

Validation fails at copy-paste

It is rather easy to input invalid values into the text boxes in these two ways:

  • Copy-paste a non-numeric values into the box.
  • Do a partial input and reposition the cursor and start typing again.

The result is included in the attached screenshot.

Screen Shot 2013-02-07 at 11 01 18 PM

Android: Cursor doesn't move to end when space/slash inserted

On formatCardNumber and formatCardExpiry, the plugin adds the space or slashes to the input box as appropriate, but the cursor doesn't move to the end. Note that the spaces/slashes are indeed added, but only after the cursor.

Tested on a Samsung Galaxy SIII running ICS using the stock browser, Dolphin, and a WebView (Chrome works correctly). On a Samsung Galaxy S 4G running Froyo (stock browser), the cursor appears to jump to the end, but further keystrokes continue to add text in the wrong place.

Screenshot_2013-02-09-21-54-11
Screenshot_2013-02-09-21-53-16

How to valid month and year as separate fileds

I did something like that

$.payment.validateCardMonthExpiry = function(month) {
var currentTime, expiry;
if (!month) {
return false;
}
month = $.trim(month);

    if (!/^\d+$/.test(month)) {
        return false;
    }

    if (!(parseInt(month, 10) <= 12)) {
        return false;
    }

   expiry = new Date(month);
   currentTime = (new Date).getMonth() + 1;
   return expiry > currentTime;
};

$.payment.validateCardYearExpiry = function(year) {
    var currentTime, expiry;

    if (!(year)) {
        return false;
    }

    year = $.trim(year);

    if (!/^\d+$/.test(year)) {
        return false;
    }

    expiry = new Date(year);
    currentTime = new Date;
    return expiry > currentTime;
};

and month value have always error

"Mobile first": using input type="number" with 'formatCardNumber' fails.

I'd prefer to use input type="number" vs. type="text" because the former prompts the number keypad on mobile devices. Unfortunately, type="number" crashes the 'formatCardNumber' method. It resets the field and fires the invalid error message on the 4th keystroke.

In the spirit of "mobile first", it would seem useful to make type="number" not fail and possibly to even make it the default input type, right?

Expiry without spaces

Hey there,

payment.js is opinionated about expiry format in that it uses spaces between month and year inside the text box (EG - MM / YYYY).

Some payment providers do not support date formats with the spaces in between the separator (MM/YYY). How can payment.js support this? Should it be a separate formatter (probably lots of code duplication here), should the expiry formatter take something like a 'noSpaces' option, or should payment.js support non-spaced expiration some other way?

Thanks for payment.js - really loving it so far!

Blake

Expiration Format

To use Stripe.js you need a separate input box for data-stripe="exp-month" and data-stripe="exp-year" so you should provide a validation that works with this format. Not just some random "Exp" format with a slash in between.

Built-in Android browser does not allow deleting the leading zero in the expiration month

This can be fixed by wrapping the $target.val statements in formatBackExpiry in a setTimeout(..., 0). I'm not sure if that'll introduce other browser compat issues though...

Strange Ctrl+Backspace behavior

On Windows, Ctrl+Backspace deletes the entire word preceding the cursor. (Compare to Mac Option+Delete.)

In a jquery.payment credit card number field, pressing Ctrl+Backspace does not behave consistently. If you press it when the field is full, it deletes the last group (as expected). However, the next press only deletes the last digit of the next remaining group, and the press after that deletes the group's remaining digits. This repeats until the field is empty. There is similar behavior in an expiration field. (Oddly, Ctrl+Delete behaves as expected.)

On Mac, Option+Delete (as it's labeled on the Mac keyboard; really backspace) behaves slightly differently in that the first Option+Delete press deletes the space after the remaining group, and the next press deletes the entire group.

Observed in Chrome 33.

On both platforms, Ctrl+Backspace / Option+Delete should probably delete the entire group behind the cursor.

restrictNumeric should not allow non-numeric values to be PASTED into a field

I am using the restrictNumeric function for a money tip filed on my form.

Right now it works good for making sure someone does not type in a non-numeric value, however it does nothing to stop them from Pasting in a string with non-numeric values. So below I submit the code I am using to do just that and would hope something could be added to the restrictNumeric function to prevent bad text being pasted into a field, the same way that the creditcard field currently works to make sure you do not paste bad text in should be added to this function please...

// The Current restrictNumeric function
restrictNumeric = function(e) {
    var input;
    if (e.metaKey || e.ctrlKey) {
        return true;
    }
    if (e.which === 32) {
        return false;
    }
    if (e.which === 0) {
        return true;
    }
    if (e.which < 33) {
        return true;
    }
    input = String.fromCharCode(e.which);
    return !!/[\d\s]/.test(input);
};

// How I am currently making it work on PASTED text,
// the same way that credit card works.
// Right now if you paste in a non-numeric value it does not 
// remove the non numeric values like it should.
$('input.price_tip').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var tip = $(element).val();
    // REMOVE NON-NUMERIC CHARACTERS
    var cleanTip = tip.replace(/\D/g,'');
    $(element).val(cleanTip);
  }, 100);
});

I published jquery.payment to npm

Hello nice people,

I find it useful to have modules published to npm to allow for easier version tracking, so I published jquery.payment to npm.

However, I am not the author. I've added maccman as an author, so hopefully that's good enough.

Please let me know if I've done a bad bad thing or if you'd like anything else.

Thank you!

$.payment.fn.formatCardCVC doesn't allow edition when text is selected.

Hi guys, hope you're fine.

I'm wondering why the restrictCVC method does not return when the text is selected. My QA team just rejected my changes because they consider that behaviour bad UX. What are the reasons why you decided to not allow CVC edition when the text is selected?

Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.