Git Product home page Git Product logo

react-native-credit-card-input's Introduction

React Native Credit Card Input

Easy (and good looking) credit-card input for your React Native Project ๐Ÿ’ณ ๐Ÿ’ณ

Code:

<CreditCardInput onChange={this._onChange} />
// or
<LiteCreditCardInput onChange={this._onChange} />

Features

  • Skeuomorphic credit-card ๐Ÿ’ณ (inspired by: card, react-native-credit-card)
  • !!NEW!! Now you could scale the Credit Card for smaller screens
  • !!NEW!! Now you could use CardView as a Component. example use case: showing saved payment details, etc.
  • Lite version for smaller screens (or if skeuomorphic is not really your thing)
  • Credit-card input validations & formatting while you're typing
  • Form is fully navigatable using keypad
  • Works on both Android and iOS

Usage

npm i --save react-native-credit-card-input

then add these lines in your react-native codebase

import { CreditCardInput, LiteCreditCardInput } from "react-native-credit-card-input";

<CreditCardInput onChange={this._onChange} />
// or
<LiteCreditCardInput onChange={this._onChange} />

// Note: You'll need to enable LayoutAnimation on android to see LiteCreditCardInput's animations
// UIManager.setLayoutAnimationEnabledExperimental(true);

And then on your onChange handler:

_onChange => form => console.log(form);

// will print:
{
  valid: true, // will be true once all fields are "valid" (time to enable the submit button)
  values: { // will be in the sanitized and formatted form
  	number: "4242 4242",
  	expiry: "06/19",
  	cvc: "300",
  	type: "visa", // will be one of [null, "visa", "master-card", "american-express", "diners-club", "discover", "jcb", "unionpay", "maestro"]
  	name: "Sam",
  	postalCode: "34567",
  },
  status: {  // will be one of ["incomplete", "invalid", and "valid"]
	number: "incomplete",
	expiry: "incomplete",
	cvc: "incomplete",
	name: "incomplete", 
	postalCode: "incomplete",
  },
};

// Notes: 
// cvc, name, & postalCode will only be available when the respective props is enabled (e.g. requiresName, requiresCVC)

Props

LiteCreditCardInput

Property Type Description
autoFocus PropTypes.bool Automatically focus Card Number field on render
onChange PropTypes.func Receives a formData object every time the form changes
onFocus PropTypes.func Receives the name of currently focused field
placeholders PropTypes.object Defaults to
{ number: "1234 5678 1234 5678", expiry: "MM/YY", cvc: "CVC" }
inputStyle Text.propTypes.style Style for credit-card form's textInput
validColor PropTypes.string Color that will be applied for valid text input. Defaults to: "{inputStyle.color}"
invalidColor PropTypes.string Color that will be applied for invalid text input. Defaults to: "red"
placeholderColor PropTypes.string Color that will be applied for text input placeholder. Defaults to: "gray"
additionalInputsProps PropTypes.objectOf(TextInput.propTypes) An object with Each key of the object corresponding to the name of the field. Allows you to change all props documented in RN TextInput.

NOTES

LiteCreditCardInput does not support requiresName, requiresCVC, and requiresPostalCode at the moment, PRs are welcome :party:

CreditCardInput

Property Type Description
autoFocus PropTypes.bool Automatically focus Card Number field on render
onChange PropTypes.func Receives a formData object every time the form changes
onFocus PropTypes.func Receives the name of currently focused field
labels PropTypes.object Defaults to
{ number: "CARD NUMBER", expiry: "EXPIRY", cvc: "CVC/CCV" }
placeholders PropTypes.object Defaults to
{ number: "1234 5678 1234 5678", expiry: "MM/YY", cvc: "CVC" }
cardScale PropTypes.number Scales the credit-card view.
Defaults to 1, which translates to { width: 300, height: 190 }
cardFontFamily PropTypes.string Font family for the CreditCardView, works best with monospace fonts. Defaults to Courier (iOS) or monospace (android)
cardImageFront PropTypes.number Image for the credit-card view e.g. require("./card.png")
cardImageBack PropTypes.number Image for the credit-card view e.g. require("./card.png")
labelStyle Text.propTypes.style Style for credit-card form's labels
inputStyle Text.propTypes.style Style for credit-card form's textInput
inputContainerStyle ViewPropTypes.style Style for textInput's container
Defaults to: { borderBottomWidth: 1, borderBottomColor: "black" }
validColor PropTypes.string Color that will be applied for valid text input. Defaults to: "{inputStyle.color}"
invalidColor PropTypes.string Color that will be applied for invalid text input. Defaults to: "red"
placeholderColor PropTypes.string Color that will be applied for text input placeholder. Defaults to: "gray"
requiresName PropTypes.bool Shows cardholder's name field
Default to false
requiresCVC PropTypes.bool Shows CVC field
Default to true
requiresPostalCode PropTypes.bool Shows postalCode field
Default to false
validatePostalCode PropTypes.func Function to validate postalCode, expects incomplete, valid, or invalid as return values
allowScroll PropTypes.bool enables horizontal scrolling on CreditCardInput
Defaults to false
cardBrandIcons PropTypes.object brand icons for CardView. see ./src/Icons.js for details
additionalInputsProps PropTypes.objectOf(TextInput.propTypes) An object with Each key of the object corresponding to the name of the field. Allows you to change all props documented in RN TextInput.

##CardView

Property Type Description
focused PropTypes.string Determines the front face of the card
brand PropTypes.string Brand of the credit card
name PropTypes.string Cardholder's name (Use empty string if you need to hide the placeholder)
number PropTypes.string Credit card number (you'll need to the formatting yourself)
expiry PropTypes.string Credit card expiry (should be in MM/YY format)
cvc PropTypes.string Credit card CVC
placeholder PropTypes.object Placeholder texts
scale PropTypes.number Scales the card
fontFamily PropTypes.string Defaults to Courier and monospace in iOS and Android respectively
imageFront PropTypes.number Image for the credit-card
imageBack PropTypes.number Image for the credit-card
customIcons PropTypes.object brand icons for CardView. see ./src/Icons.js for details

Note on additionalInputsProps

additionalInputsProps gives you more control over the inputs in LiteCreditCardInput and CreditCardInput. An example object is as follows:

addtionalInputsProps = {
  name: {
    defaultValue: 'my name',
    maxLength: 40,
  },
  postalCode: {
    returnKeyType: 'go',
  },
};

The above would set the default value of the name field to my name and limit the input to a maximum of 40 character. In addition, it would set the returnKeyType of the postalcode field to go.

Methods

setValues

Set values into credit card form

	// sets 4242 on credit card number field
	// other fields will stay unchanged
	this.refs.CCInput.setValues({ number: "4242" });

Known issues: clearing a field e.g. setValues({ expiry: "" }) will trigger the logic to move to previous field and trigger other kind of weird side effects. PR plz

focus

focus on to specified field

	// focus to expiry field
	this.refs.CCInput.focus("expiry");

Example

Expo Snack

In the example directory, run:

npm install

react-native run-ios
# or
react-native run-android

Missing Something? Something is not working?

  • Open a GitHub issue, or
  • Send a pull request :D
  • Make sure npm run lint passed

Future Improvement

Breaking Changes from 0.2.*

  • cardViewSize prop are removed from CreditCardInput, use cardScale instead (because changing the size will break most of the texts)
  • bgColor prop are removed from CreditCardInput, ask your designer friend to make a credit card image instead (or use the prebundled image)
  • imageFront and imageBack props are renamed to cardImageFront and cardImageBack respectively,
  • Android monospace fonts doesn't looks as nice as iOS Courier, bundle custom fonts into your app and override the default using cardFontFamily instead

Production App using react-native-credit-card-input

  • Grain.com.sg (iOS, Android) โ€“ Gourmet food delivery in Singapore

react-native-credit-card-input's People

Contributors

andreyco avatar coolses avatar kraffslol avatar sbycrosz avatar sscaff1 avatar wchaering 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

react-native-credit-card-input's Issues

[Question]: Reseting Card FormData

Hello @sbycrosz, thanks for sharing this package. Got a question, please is there a way to reset the form data/values such as in a lifecycle event like componentWillUnmount or even after data is retrieved and form is submitted etc?

Thanks.

placeholder colour not reflecting

Hi All,

I need to change the placeholder colour but it was not reflecting. It remains the default colour.
When i try to change other text colours they got changed.
Here is sample code.

<CreditCardInput
requiresName={true}
cardFontFamily={"Kabel Bk BT"}
placeholderColor={"white"}
inputContainerStyle={{
borderBottomWidth: 1, borderBottomColor:Constants.Colors.White
}}
onChange={this._onChange}
labelStyle={[styles.label,Constants.Fonts.content]}
inputStyle={[styles.input,Constants.Fonts.content]}
autoFocus={false}/>

Creditcard input miss positioned

i think this is due to position absolute in the cardview but take a look of my view
screenshot_1511754079

i tried to change the style but it stays and stuck there, anyone know how to solve this?
i fix it by putting padding to the input, but i guess it will not be effective in all phone

Input labels

Is is possible to rename (translate) input fields through additionalInputProps?

Thank you :)

Option to manually set CC values?

Hello!
I'm trying to set the card values manually but I can't seem to figure out how to do it (If even possible).

I tried adding

values={{expiry: "11/11"}}

prop to the CreditCardInput component but it seems like the values prop doesn't get set.

Is there a way to set the initial values yet?

Card number input loses focus to expiry after 12 numbers entered

Hi all,

While trying to enter account numbers like 5017670000005900 the card number using the phone keypad text input loses focus after entering only 12 numbers instead of 16 and focus moves to expiry. Couldn't find any props or options in documentation.

"react-native": "0.47.0",
"react-native-credit-card-input": "0.3.3"

Please Help.

No onBlur prop?

Hi, first off, nice work on this project!

I was hoping to use an onBlur event on the input like with a regular React Native TextInput component... could this be added?

Thanks!

CardView prop for Text Color

Looking for a prop to change the color of the baseText, placeholder & focused text on the CardView Component.

I've changed the hardcoded values but everytime I "yarn upgrade" it overwrites the values.

Could you please add this.

Thanks,
Lewis

Initial state of card is backwards

I am a using CreditCardInput with autoFocus and when the screen initially renders, the back of the card image is shown. As soon as I enter something, the front of the card image is shown. It doesn't flip to the front image, it just appears. As I type, when I get to CVV, it does flip to the back, as it should. It is just that when the screen is initially rendered, the back card image is shown, but it should be the front card image.

Here is the relevant code:

<CreditCardInput
  autoFocus
  inputStyle={styles.creditCardInput}
  onChange={this.onChange}
/>

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  creditCardInput: {
    color: textColor
  }
})

I am using react-native-credit-card-input 0.3.3 and react-native-flip-card 3.3.3

Plugin allows entering 18 digits as card number

Hi!
Thank you for the component.
The issue is not major, obviously.

Entering last digit of card, then switching to expiration and back using backspace allows entering 18 digits. Not sure, if this is a bug or feature.

screenshot 2017-04-18 05 11 33

Latest version

Order of postal code and cardholder's name

Hello!

Is there an option to show the postal code field before the cardholder's name field? Since there's no auto next focus for the name and the name field extends to the edge of the screen, the postal code box is effectively hidden.

Export CC Icons

This may be the laziest request ever, but the font awesome CC icons are not named as nicely as the ones in this library. Stripe card brand strings can be

Visa, American Express, MasterCard, Discover, JCB, Diners Club, or Unknown.

I want to display a list of cards with only icons - not the full cardview (it wont fit nicely in a typical listview), and I dont want to write a switch statement for converting stripe brand to font awesome names.

Im going to submit a PR to export the icons. A lot of text for a very small, pointless change. Maybe there is another soul who can find use in this.

RN 0.39 broken container

Hi,
Missed flex: 1 in CreditCardInput.js row 18 .

container: { alignItems: "center", flex: 1 },

Regards

Inputs styles

Hello, is it possible to set width to input fields passing it trough props?

Very slow when used on a mobile device but runs fine in xcode

Hello!
Thank you so much for creating this component, it has been very useful.

When I was integrating this component into my application it would run super fast and smooth during development in xcode. But when I deployed to production it is super slow and laggy.
Do you happen to know what I am doing wrong or is this a reoccurring issue.

Tested on multiple iPhones.

Improve set focus to previous field logic

I'm writing this as documentations & pleas for help

Currently CCInput set focus to the previous field when a field become empty. e.g. when user changes expiry from "1" to "" with backspace button, CCInput will focus to number field. This will not allow user to removes expiry without triggering the set focus to the previous field logic.

The better logic is to move to previous field when user press backspace on an empty field (following stripe implementation).

The catch is onKeypress prop is not available for RN Android atm, so some workaround might be needed.

PRs are welcome! ๐ŸŽ‰

Error browserify: export * from "./src/"; in index.js:1

Hi,
Sorry I'm relatively new in the NodeJs world.
When I use browserify in my project I have this error since I use the 'react-native'credit-cart-input' module:

[00:35:17] Starting 'browserify'...
Error :
D:\dev\myproject\node_modules\react-native-credit-card-input\index.js:1
export * from "./src/";
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

Here my gulp task for Browserify:

gulp.task('browserify', function(){
    return browserify({
        extensions: ['.js', '.jsx', '.es6', '.json'],
        entries: 'src/js/main.jsx',
    })
    .transform(babelify.configure({
        presets: ["es2015","react"],
    }))
    .bundle()
    .on("error", function (err) { console.log("Error : " + err.message); })
    .pipe(source('main.js'))
    .pipe(gulp.dest(path.DIST_JS));
});

I see the project use eslint, may be something is missing about this in my dev environnement.

Can you help me ?

Attempting to use `this.refs.CCInput.setValues({ number: "4242" });` but receiving, "undefined is not an object."

I'm currently attempting to use this.refs.CCInput.setValues({ number: "4242" }); in my component to update the number value generated in the CreditCardInput component, but keep receiving, "undefined is not an object." Anyone have any thoughts on how to get this to work? I've pasted a snippet of code below:


<CreditCardInput 
        ... 
/>

<TextInput
	onChangeText={(value) => this.refs.CCInput.setValues({ number: value })}
        ...
/>

Postal code field doesnt accept US ZIP codes

Postal Code field doesn't return true for valid US ZIP codes. It expects 6 digits to return true.

connectToState.js line 38

validatePostalCode: (postalCode = "") => {
return postalCode.match(/^\d{6}$/) ? "valid" : <--- this has to check for both 5 and 6 digits
postalCode.length > 6 ? "invalid" :
"incomplete";
},

LiteCreditCardInput input focusing breaks with RN version > 0.37 (Release Build Configuration)

I recently noticed that focusing of CCInput components in LiteCreditCardInput is not working as expected only when my project's build configuration is set to Release.

  • I was using react-native-credit-card-input v0.2.6, but am experiencing this same issue with v0.3.3.
  • I've confirmed this issue with React Native versions 0.38, 0.39, and 0.40.
  • Temporarily reverting to React Native 0.37 has allowed me to work around this for now.

I'd appreciate any insight or ideas about why this might be happening.

Thanks!

keyboardShouldPersistTaps deprecation warning

When mounting a simple card input:
<CreditCardInput onChange={this.handleCardChange} />;

a deprecation warning is thrown:
Warning: 'keyboardShouldPersistTaps={true}' is deprecated. Use 'keyboardShouldPersistTaps="always"' instead

setValues() on full card number or full expiry raises an error

Attempt to measure layout but offset or dimensions were NaN

EDIT: On further investigation, only causes error if card or expiry is valid. Invalid values do not cause the error. This is probably caused by the fact that a valid value on either of these fields attempts to focus on the next value.

Broken on RN37

There's a breaking change on RN36 on flex properties. Both of the forms seem broken.

Export icons for use elsewhere

It'd be great if the icons were exported in the package so that they can be used elsewhere.

For example, in our app, we want to show what (usually stored) payment method will be charged and we want to show a consistent icon. We can obviously use credit-card-type to discover the type of card, but we can't show the right icon without this being exported.

Input is Invisible

I am having trouble getting this component to show up. The input is not visible. I am on RN 0.36.0 and this is for iOS. Any help appreciated! Here is what it looks like:

img_8414

allowsScroll prop not working

Enabling horizontal scrolling would alleviate the issue of it being difficult to navigate left/right through input fields, however setting the prop does not work.

Porting to React for web?

This repo looks amazing.

Not too familiar with React Native, how much work would it take to port this to React for the web?

Any info would be much appreciated.

get error immediately when i import

i got an error after i import the component
did anyone got same error??

https://imgur.com/05jKbXR

Unhandled JS Exception: Cannot read property 'string' of undefined
Unhandled JS Exception: Module AppRegistry is not a registered callable module (calling runApplication)

Accessibility not passing up to each CCInput

I am trying to automate some tests on Appium and I am able to create accessibilityLabel, accessibilityTraits, and accessible up to other Components, but when I try to do it using your open source library, it doesn't work. Have you guys experienced this issue before and how would you go about resolving it?

Thanks.

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.