ciam-six-digits-input.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { forwardRef } from 'react'
  2. import { Form, FormControlProps } from 'react-bootstrap'
  3. import classnames from 'classnames'
  4. interface CIAMSixDigitsInputProps extends FormControlProps {
  5. value: string | undefined
  6. }
  7. const separator = '\u2007' // figure space
  8. const CIAMSixDigitsInput = forwardRef<
  9. HTMLInputElement,
  10. CIAMSixDigitsInputProps
  11. >(({ className, onChange, value, ...props }, ref) => {
  12. const group1 = value?.slice(0, 3) || ''
  13. const group2 = value?.slice(3, 6) || ''
  14. const displayValue = group2 ? `${group1}${separator}${group2}` : group1
  15. return (
  16. <div className="ciam-six-digits-container">
  17. <Form.Control
  18. ref={ref}
  19. {...props}
  20. size="lg"
  21. onChange={v => {
  22. const inputValue = v.target.value
  23. const sanitizedValue = inputValue.replaceAll(/\D/g, '').slice(0, 6)
  24. onChange?.({
  25. ...v,
  26. target: { ...v.target, value: sanitizedValue },
  27. currentTarget: { ...v.currentTarget, value: sanitizedValue },
  28. })
  29. }}
  30. value={displayValue}
  31. className={classnames(
  32. 'form-control-ds ciam-six-digits-input',
  33. className
  34. )}
  35. maxLength={7}
  36. inputMode="numeric"
  37. autoComplete="off"
  38. data-1p-ignore
  39. />
  40. {group1.length > 0 && (
  41. <span className="ciam-six-digits-dash" aria-hidden>
  42. -
  43. </span>
  44. )}
  45. </div>
  46. )
  47. })
  48. CIAMSixDigitsInput.displayName = 'CIAMSixDigitsInput'
  49. export default CIAMSixDigitsInput