Skip to content

Commit

Permalink
feat: add input masking to guide correct entry of the Social Security…
Browse files Browse the repository at this point in the history
… Number tckt-364
  • Loading branch information
kalasgarov committed Nov 22, 2024
1 parent 5930c69 commit 6ef7fee
Showing 1 changed file with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,26 @@ import { type SocialSecurityNumberProps } from '@atj/forms';

import { type PatternComponent } from '../../index.js';

const formatSSN = (value: string) => {
const rawValue = value.replace(/[^\d]/g, '');
if (rawValue.length <= 3) return rawValue;
if (rawValue.length <= 5)
return `${rawValue.slice(0, 3)}-${rawValue.slice(3)}`;
return `${rawValue.slice(0, 3)}-${rawValue.slice(3, 5)}-${rawValue.slice(5, 9)}`;
};

export const SocialSecurityNumberPattern: PatternComponent<
SocialSecurityNumberProps
> = ({ ssnId, hint, label, required, error, value }) => {
const { register } = useFormContext();
const { register, setValue } = useFormContext();
const errorId = `input-error-message-${ssnId}`;
const hintId = `hint-${ssnId}`;

const handleSSNChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const formattedSSN = formatSSN(e.target.value);
setValue(ssnId, formattedSSN, { shouldValidate: true });
};

return (
<fieldset className="usa-fieldset">
<div className={classNames('usa-form-group margin-top-2')}>
Expand Down Expand Up @@ -42,7 +55,11 @@ export const SocialSecurityNumberPattern: PatternComponent<
type="text"
defaultValue={value}
{...register(ssnId, { required })}
aria-describedby={`${hint ? `${hintId}` : ''}${error ? ` ${errorId}` : ''}`.trim() || undefined}
onChange={handleSSNChange}
aria-describedby={
`${hint ? `${hintId}` : ''}${error ? ` ${errorId}` : ''}`.trim() ||
undefined
}
/>
</div>
</fieldset>
Expand Down

0 comments on commit 6ef7fee

Please sign in to comment.