I am implementing a react component that formats a 9-digit number as a social security number in the format: xxx-xx-xxxx.
Unfortunately, I'm not able to select all (ctrl + a) and delete the ssn, probably due to my "keyup" function in the handleSSN() click handler. The "value" attribute of the Input component takes the nine digit number that the user inputs, and the formatSSN() function formats the number to appear as "xxx-xx-xxxx" in the input field. When a user tries to select all and delete what they have input in the field, the highlighted content will simply become un-highlighted when the user lifts the key up. Is there a way to accommodate for the "ctrl + a" behavior in this handler?
This functionality is heavily based on: http://jsfiddle.net/hughdidit/Y5SK6/ , which has the same issue of not being able to "ctrl+ a" the input box and delete the content. Any insight is greatly appreciated
<FormLabel clear="both" float="left">
Social Security Number:
</FormLabel>
<Input
data-testId="ssn-input"
border="1px solid #E2E8F0"
background="#FFFFFF"
borderRadius="4px"
placeholder="Text here"
color="grey.900"
value={formatSSN(userResponse)}
onChange={(e) => handleChangeSSN(e.target)}
onBlur={(e) => handleChangeSSN(e.target)}}
/>
formatSSN function (this doesn't have to do with the problem at hand, but is how the ssn is displayed in the input when the component loads, if an ssn is already in the database):
export const formatSocialSecurity = (val) => {
val = val && val.replace(/\D/g, '');
val = val && val.replace(/^(\d{3})/, '$1-');
val = val && val.replace(/-(\d{2})/, '-$1-');
val = val && val.replace(/(\d)-(\d{4}).*/, '$1-$2');
return val;
};
The handleSSN() click handler function saves the value to the state (not shown below) after doing some validations itself:
const handleChangeSsn = ({ value }) => {
var keyCode = value.which || value.keyCode || 0;
console.log(keyCode);
document
.getElementById('ssn-input')
.addEventListener('keyup', function (event) {
let val = this.value.replace(/\D/g, '');
let newVal = '';
if (val.length > 4) {
this.value = val;
}
if (val.length > 3 && val.length < 6) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
if (val.length > 5) {
newVal += val.substr(0, 3) + '-';
newVal += val.substr(3, 2) + '-';
val = val.substr(5);
}
newVal += val;
this.value = newVal;
});