I have a text field that prevents non-numeric input and formats a social security number with dashes. (999-99-9999) Example is below.
I have encountered a problem where if I input a ssn (eg. "123456789") then delete the text "3-45-6" (text display is now "12789") then insert the missing numbers "3456" too quickly the numbers are in the wrong order. The display as "123-46-5789". 6 and 5 are transposed. I have tried this a number of times so I know I am not fat fingering. I must type very fast for this to happen but it does occur with regularity. If I type slower it works fine. I tried disabling the field in my reformat script, but it did not fix it.
Any ideas as to how I can prevent this from happening?
Thanks,
Matt
<html>
<script>
function formatSSN(formName, inputName){
//format input in 999-99-9999 format
//reformat if a character key was entered
if(window.event.keyCode > 47){
inputField = eval( 'document.'+ formName +'.' + inputName );
var ssnValue = inputField.value;
//save caret position
var caretPos = getCaretPosition(inputField);
if(caretPos == 4|| caretPos == 7 || caretPos >= ssnValue.length)
caretPos = caretPos + 1;
//**disabled input here but does not prevent bad input
//inputField.disabled = true; //prevent user input while
js is executing
//strip out any non-numeric content
ssnValue = removeNonNumerics(ssnValue);
//add hyphen
ssnValue = addFormatHyphen(ssnValue);
inputField.value = ssnValue;
//**disable attempt did not prevent error
//inputField.disabled = false;
//inputField.focus();
//reposition the cursor if not at beginning
if(caretPos > 1){
setSelectionRange(inputField, caretPos, caretPos);
}
}
}
function addFormatHyphen(ssn){
var ssnLength = ssn.length;
//add format hyphen
if(ssnLength > 5){
ssn =
(ssn.substr(0,3) + "-"+
ssn.substr(3,2) + "-" +
ssn.substr(5)).substr(0,11);
}else if(ssnLength > 3){
ssn =
ssn.substr(0,3) + "-"+
ssn.substr(3);
}
return ssn;
}
function removeNonNumerics(checkString){
rExp = /[^0-9]/g;
return checkString.replace(rExp,"");
}
function getCaretPosition(objTextBox){
var objTextBox = window.event.srcElement;
var i = objTextBox.value.length;
if (objTextBox.createTextRange){
objCaret = document.selection.createRange().duplicate();
while (objCaret.parentElement()==objTextBox &&
objCaret.move("character",1)==1) --i;
}
return i;
}
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
</script>
<form name=myForm method=POST >
Social Security <input type=text name=SSN onkeyup="formatSSN('myForm', this.name)" size=11 maxlength=11 >
</form>
</html>