UNPKG

@blocklet/payment-react

Version:

Reusable react components for payment kit v2

83 lines (82 loc) 1.39 kB
import isPostalCode from "validator/lib/isPostalCode"; import { t } from "../locales/index.js"; const POSTAL_CODE_SUPPORTED_COUNTRIES = [ "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, country) { if (!postalCode) return true; const countryUpper = country?.toUpperCase(); const isSupported = country && POSTAL_CODE_SUPPORTED_COUNTRIES.includes(countryUpper); try { return isPostalCode(postalCode, isSupported ? countryUpper : "any"); } catch (error) { console.error(error); return false; } } export function getFieldValidation(fieldName, validations, locale = "en") { if (!validations || !validations[fieldName]) return {}; const fieldValidation = validations[fieldName]; const rules = {}; if (fieldValidation.pattern) { rules.pattern = { value: new RegExp(fieldValidation.pattern), message: fieldValidation.pattern_message?.[locale] || t("payment.checkout.invalid", locale) }; } return rules; }