I want to copy a US format phone number and paste it to my field .
If I copy (456)-123-0596 to the field only 456123 is copied to the field.
But I want it to be like the format.
The input field is restricted only for numbers using pattern and maximum length is 10.
onCheckInput(e) {
const onlyNums = e.target.value.replace(/[^0-9]/g, '');
if (onlyNums.length < 10) {
e.target.value = onlyNums;
} else if (onlyNums.length === 10) {
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');
e.target.value = number;
}
}
formatPhoneNumber(number) {
if (number && number != 0) {
number = number.replace(/-/g, '');
number = number.replace('(', '');
number = number.replace(') ', '');
number = number.replace(')', '');
return '(' + number.substr(0, 3) + ')-' + number.substr(3, 3) + '-' + number.substr(6, 4);
}
return '';
}
<Field name="HomePhone"
onInput={this.onCheckInput} maxLength="10"
pattern="\d*" component="input" type="text"
placeholder="HomePhone"
title={' Home Phone: ' + this.formatPhoneNumber(patientInfo.HomePhone)}
/>
How can I remove the braces and hyphens on Paste and save them in the Phone number format?
I've modified the code as below:
onCheckInput(e) {
const onlyNums = e.target.value.replace(/[^0-9]/g, '');
if (onlyNums != e.target.value.replace(/[^\d\.]/g,""))
{onlyNums.replace(/[^\d\.]/g,"");
}
if (onlyNums.length < 10) {
e.target.value = onlyNums;
} else if (onlyNums.length === 10) {
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');
e.target.value = number;
}
}
When I debugged I found that Since maxLength1s 10 (456)-123- is read and removed braces and hyphens from this input.
How can I get this format with maxLength=10?