Created
April 8, 2020 20:38
-
-
Save stephenway/32d4a3842f1be3bbf3ecd49bd64c294d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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