UNPKG

@navinc/base-react-components

Version:
51 lines 3.18 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { jsx as _jsx } from "react/jsx-runtime"; import { useMemo, useEffect, useCallback } from 'react'; import { Input } from '../input.js'; import { useField } from 'formik'; import styled from 'styled-components'; import { inputPattern } from '@navinc/utils'; const createZipCodeValidator = ({ isRequired = false, requiredErrorMessage = 'Zip is required', minLengthErrorMessage = 'We need your 5-digit zip code', nineDigitLengthErrorMessage = 'We need your 5-digit or 9-digit zip code', } = {}) => (zip) => { if (isRequired && !zip) { return [requiredErrorMessage]; } if (zip && zip.length < 5) { return [minLengthErrorMessage]; } if (zip && zip.length > 5 && zip.length < 10) { return [nineDigitLengthErrorMessage]; } }; const _ZipCodeInput = (_a) => { var { name, onBlur, onChange, invalidOnTouched = true, isRequired, requiredErrorMessage, minLengthErrorMessage, nineDigitLengthErrorMessage, restrictToFiveDigits } = _a, props = __rest(_a, ["name", "onBlur", "onChange", "invalidOnTouched", "isRequired", "requiredErrorMessage", "minLengthErrorMessage", "nineDigitLengthErrorMessage", "restrictToFiveDigits"]); const memoizedValidateZipCode = useMemo(() => createZipCodeValidator({ isRequired, requiredErrorMessage, minLengthErrorMessage, nineDigitLengthErrorMessage }), [isRequired, requiredErrorMessage, minLengthErrorMessage, nineDigitLengthErrorMessage]); const [field, meta, { setValue }] = useField({ name, validate: memoizedValidateZipCode }); const pattern = restrictToFiveDigits ? '99999' : '99999-9999'; const convertToPattern = useCallback((value) => inputPattern(value !== null && value !== void 0 ? value : '', pattern), [pattern]); useEffect(() => { const converted = convertToPattern(field.value); if (converted !== field.value) { // Ensure initial value stored in parent form is formatted correctly setValue(converted); } }, [convertToPattern, field.value, setValue]); return (_jsx(Input, Object.assign({ type: "text", inputMode: "numeric", name: name, value: convertToPattern(field.value), onChange: (e) => { setValue(convertToPattern(e.target)); onChange && onChange(e); }, onBlur: (e) => { field.onBlur(e); onBlur && onBlur(e); }, errors: (!invalidOnTouched || meta.touched) && meta.error, isInvalid: (!invalidOnTouched || meta.touched) && !!meta.error, hasSpaceForErrors: true }, props))); }; export const ZipCodeInput = styled(_ZipCodeInput).withConfig({ displayName: "brc-sc-ZipCodeInput", componentId: "brc-sc-1xnndtw" }) ``; //# sourceMappingURL=zip-code-input.js.map