Repository URL to install this package:
|
Version:
3.1.1 ▾
|
import * as React from 'react'
import {
errorMessageFor,
isValidSecurityCode,
isValidCreditCard,
} from '../../../validators'
import { Value } from '../../typings'
import { ObserverInput } from '../../inputs/ObserverInput'
import { InputState } from '../../inputs/InputState'
import { ExpiryDatePlugin } from '../CreditCardExpiryDatePlugin'
import { CreditCardPluginProps, CreditCardPluginNestedState } from './typings'
const securityCodeValidator = (value: Value) =>
isValidSecurityCode(value as string) || errorMessageFor('securityCode')
const creditCardValidator = (value: Value) =>
isValidCreditCard(value as string) || errorMessageFor('creditCard')
class CreditCardPlugin extends React.Component<CreditCardPluginProps> {
static isSatisfiedByProps(props: { type: string }): boolean {
return props.type === 'creditCard'
}
static defaultState = (inputState: InputState) => {
// @todo could move this to `CreditCardState`
const cardNumberState = new InputState()
const cvvState = new InputState()
const expiryDateState = new InputState()
// adds attributes
ExpiryDatePlugin.defaultState(expiryDateState)
cvvState.setValidator(securityCodeValidator)
cardNumberState.setValidator(creditCardValidator)
inputState.attributes.creditCardState = {
cardNumberState,
cvvState,
expiryDateState,
} as CreditCardPluginNestedState
return {
serialize: ($inputState: InputState) => {
return {
cardNumber: cardNumberState.toJSON(),
cvv: cvvState.toJSON(),
expiryDate: expiryDateState.toJSON(),
}
},
validate: (value: Value) => {
return (
cardNumberState.isValid && cvvState.isValid && expiryDateState.isValid
)
},
}
}
render() {
const { state, ...props } = this.props
const {
cardNumberState,
cvvState,
expiryDateState,
} = state.attributes.creditCardState!
// change (setValue), blur (validate, props onblur)
/**
* <>
* <card #>
* <>
* <expire year>
* <expire month>
* </>
* <cvv>
* </>
*/
return (
<>
<ObserverInput
state={cardNumberState}
autoComplete="cc-number"
label="credit card number"
pattern="[0-9\- ]+"
minLength={7}
maxLength={16}
/>
<ExpiryDatePlugin state={expiryDateState} />
<ObserverInput
state={cvvState}
autoComplete="cc-csc"
label="ccv (?)"
type="number"
pattern="([\d][\d][\d])"
minLength={3}
maxLength={3}
max={999}
/>
</>
)
}
}
export { CreditCardPlugin }
export default CreditCardPlugin