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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 89x 89x | import React from "react";
import { RHFInput } from "@common/Input";
import { useFormContext } from "react-hook-form";
type SSNInputProps = {
id?: string;
name: string;
label?: string;
placeholder?: string;
disabled?: boolean;
inputStyle?: React.CSSProperties;
customProps?: {
maxLength: number;
};
focusViewColor?: string;
helper?: string;
};
const normalizeInput = (value: string, isDirty: boolean, isEIN: boolean) => {
if (!value) return value;
// Initially, the 'X' can be included, but after that, only digits should be allowed. It also needs to be normalized at the start, or else the data in the form won't be prefilled, or it will cause validation errors.
const regexPattern = isDirty ? /\D/g : /[^\dX]/g;
const cleanedValue = value.replace(regexPattern, "");
const segments = !isEIN
? [
cleanedValue.slice(0, 3),
cleanedValue.slice(3, 5),
cleanedValue.slice(5, 9),
] // SSN Format: XXX-XX-XXXX
: [cleanedValue.slice(0, 2), cleanedValue.slice(2, 10)]; // EIN Format: XX-XXXXXXX
return segments.filter(Boolean).join("-");
};
const SSNInput = ({
disabled,
label,
name,
placeholder,
inputStyle = {},
customProps,
...rest
}: SSNInputProps) => {
const { setValue, watch, getFieldState } = useFormContext();
React.useEffect(() => {
const { isDirty } = getFieldState(name);
const isEIN = customProps?.maxLength === 10;
const value = watch(name);
setValue(name, normalizeInput(value, isDirty, isEIN));
}, [watch(name)]);
return (
<RHFInput
disabled={disabled}
name={name}
label={label}
placeholder={placeholder}
fullWidth
inputProps={{
maxLength: customProps?.maxLength
? String(customProps.maxLength)
: "11",
}}
sx={{
letterSpacing: "4px",
"& .MuiFormHelperText-root": {
letterSpacing: "0px",
},
"& .MuiInputBase-root": {
...inputStyle,
},
}}
{...rest}
/>
);
};
export default SSNInput;
|