All files / app/payment/storedInstrument getInstrumentValidationSchema.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  41x 41x 41x 41x   41x                                 41x 8x 8x 8x 8x 8x   8x         8x 7x       5x 5x 5x   5x         8x 5x       3x       3x       8x    
import { LanguageService } from '@bigcommerce/checkout-sdk';
import { memoize } from '@bigcommerce/memoize';
import { cvv, number } from 'card-validator';
import creditCardType from 'credit-card-type';
import { object, string, ObjectSchema, StringSchema } from 'yup';
 
import mapFromInstrumentCardType from './mapFromInstrumentCardType';
import { CardInstrumentFieldsetValues } from './CardInstrumentFieldset';
 
export interface InstrumentValidationSchemaOptions {
    instrumentBrand: string;
    instrumentLast4: string;
    isCardCodeRequired: boolean;
    isCardNumberRequired: boolean;
    language: LanguageService;
}
 
interface InstrumentValidationSchema {
    ccCvv?: StringSchema;
    ccNumber?: StringSchema;
    instrumentId: StringSchema;
}
 
export default memoize(function getInstrumentValidationSchema({
    instrumentBrand,
    instrumentLast4,
    isCardCodeRequired,
    isCardNumberRequired,
    language,
}: InstrumentValidationSchemaOptions): ObjectSchema<CardInstrumentFieldsetValues> {
    const schema: InstrumentValidationSchema = {
        instrumentId: string()
            .required(),
    };
 
    if (isCardCodeRequired) {
        schema.ccCvv = string()
            .required(language.translate('payment.credit_card_cvv_required_error'))
            .test({
                message: language.translate('payment.credit_card_cvv_invalid_error'),
                test(Ivalue = '') {
                    const cardType = mapFromInstrumentCardType(instrumentBrand);
                    const cardInfo = creditCardType.getTypeInfo(cardType);
 
                    return cvv(value, cardInfo && cardInfo.code ? cardInfo.code.size : undefined).isValid;
                },
            });
    }
 
    if (isCardNumberRequired) {
        schema.ccNumber = string()
            .required(language.translate('payment.credit_card_number_required_error'))
            .test({
                message: language.translate('payment.credit_card_number_invalid_error'),
                test: (Ivalue = '') => number(value).isValid,
            })
            .test({
                message: language.translate('payment.credit_card_number_mismatch_error'),
                test: (Ivalue = '') => value.slice(-instrumentLast4.length) === instrumentLast4,
            });
    }
 
    return object(schema);
});