UNPKG

@blocklet/payment-react

Version:

Reusable react components for payment kit v2

85 lines (82 loc) 1.56 kB
import isPostalCode, { PostalCodeLocale } from 'validator/lib/isPostalCode'; import { t } from '../locales'; const POSTAL_CODE_SUPPORTED_COUNTRIES: PostalCodeLocale[] = [ 'AD', 'AT', 'AU', 'BE', 'BG', 'BR', 'CA', 'CH', 'CN', 'CZ', 'DE', 'DK', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HU', 'ID', 'IE', 'IL', 'IN', 'IR', 'IS', 'IT', 'JP', 'KE', 'KR', 'LI', 'LT', 'LU', 'LV', 'MX', 'MT', 'NL', 'NO', 'NZ', 'PL', 'PR', 'PT', 'RO', 'RU', 'SA', 'SE', 'SI', 'SK', 'TN', 'TW', 'UA', 'US', 'ZA', 'ZM', ]; export function validatePostalCode(postalCode: string, country?: string): boolean { if (!postalCode) return true; const countryUpper = country?.toUpperCase(); const isSupported = country && POSTAL_CODE_SUPPORTED_COUNTRIES.includes(countryUpper as PostalCodeLocale); try { return isPostalCode(postalCode, isSupported ? (countryUpper as PostalCodeLocale) : 'any'); } catch (error) { console.error(error); return false; } } export function getFieldValidation(fieldName: string, validations?: Record<string, any>, locale: string = 'en') { if (!validations || !validations[fieldName]) return {}; const fieldValidation = validations[fieldName]; const rules: Record<string, any> = {}; if (fieldValidation.pattern) { rules.pattern = { value: new RegExp(fieldValidation.pattern), message: fieldValidation.pattern_message?.[locale] || t('payment.checkout.invalid', locale), }; } return rules; }