UNPKG

pagamio-frontend-commons-lib

Version:

Pagamio library for Frontend reusable components like the form engine and table container

49 lines (48 loc) 2.4 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import React, { forwardRef, useCallback, useState } from 'react'; import { Input } from '../../../../components'; const CardExpiryInput = forwardRef(({ field, error, value, onChange, ...props }, ref) => { const [formattedValue, setFormattedValue] = useState(''); // Format expiry date with slash const formatExpiry = useCallback((input) => { const numbers = input.replace(/\D/g, ''); if (numbers.length >= 2) { return `${numbers.slice(0, 2)}/${numbers.slice(2, 4)}`; } return numbers; }, []); // Validate month value const isValidMonth = useCallback((month) => { const monthNum = parseInt(month, 10); return monthNum >= 1 && monthNum <= 12; }, []); // Handle input change const handleChange = useCallback((e) => { const input = e.target.value; const numbers = input.replace(/\D/g, ''); // Prevent more than 4 digits if (numbers.length > 4) return; // Validate month when 2 digits are entered if (numbers.length >= 2) { const month = numbers.slice(0, 2); if (!isValidMonth(month)) return; } const formatted = formatExpiry(numbers); setFormattedValue(formatted); // Call parent onChange with raw numeric value if (onChange) { onChange(numbers); } }, [formatExpiry, isValidMonth, onChange]); // Handle initial value formatting React.useEffect(() => { if (value) { setFormattedValue(formatExpiry(value)); } }, [value, formatExpiry]); return (_jsxs("div", { children: [_jsx("label", { htmlFor: field.name, className: "block text-sm font-medium text-gray-700", children: field.label }), _jsx(Input, { ...props, id: field.name, ref: ref, value: formattedValue, onChange: handleChange, disabled: field.disabled, placeholder: field.placeholder || 'MM/YY', maxLength: 5, inputMode: "numeric", pattern: "\\d*", className: `mt-1 block w-full p-2 border ${error ? 'border-red-500' : 'border-gray-300'} rounded-md shadow-sm disabled:text-gray-400 disabled:bg-gray-50` }), error && _jsx("p", { className: "mt-2 text-sm text-red-500", children: error.message })] })); }); CardExpiryInput.displayName = 'CardExpiryInput'; export default CardExpiryInput;