Skip to content

Instantly share code, notes, and snippets.

@stephenway
Created April 8, 2020 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenway/32d4a3842f1be3bbf3ecd49bd64c294d to your computer and use it in GitHub Desktop.
Save stephenway/32d4a3842f1be3bbf3ecd49bd64c294d to your computer and use it in GitHub Desktop.
import { useField } from 'formik'
import React from 'react'
import StringMask from 'string-mask'
import TextField from '@material-ui/core/TextField'
const DELIMITER = '-'
const MASK = '000-000-0000'
function removeTrailingCharIfFound(str: string, char): string {
return str
.split(char)
.filter(segment => segment !== '')
.join(char)
}
function formatValue(str: string): string {
const formatter = new StringMask(MASK)
const unmaskedValue = str.split(DELIMITER).join('')
const formatted = formatter.apply(unmaskedValue)
const cleanFormatted = removeTrailingCharIfFound(formatted, DELIMITER)
return cleanFormatted
}
const PhoneField = props => {
const { name, validate, ...other } = props
const [field, meta] = useField({ name, validate })
const { onChange, ...otherField } = field
const fieldError = meta.error
const showError = meta.touched && !!fieldError
return (
<TextField
{...other}
{...otherField}
variant="outlined"
fullWidth
error={showError}
helperText={showError ? fieldError : props.helperText}
onChange={event => {
onChange(event.target.name)(formatValue(event.target.value))
}}
/>
)
}
export default PhoneField
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment