Formatting windows product keys dynamically
I am working on a project and they want to have the product keys automatically add the dashes and capitalize the key. The following code will work for that as long as you type the product key all at once and do not have to edit anything in the middle. My question is how would you "properly" format the product key in: xxxxx-xxxxx-xxxxx-xxxxx-xxxxx.
Code:
function productKey(data, e) {
// Get the product key you are typing
var productKey = data.value;
// Capture the code for the key just pressed
var KeyID = (window.event) ? event.keyCode : e.keyCode;
// Capitalize the product key
productKey = productKey.toUpperCase();
// Find the key length
var keyLength = productKey.length;
switch(KeyID) {
case 8: // Backspace key was pressed
// Determine if we need to remove an extra character due to
// removing the slash that we automatically added
switch(keyLength % 6) {
case 5:
if(keyLength>4) {
// Delete one extra character
productKey = productKey.substr(0, (keyLength-1));
}
break;
}
break;
default:
// Determine if we need to add a - or not
switch(keyLength % 6) {
case 5: // We just typed the 5th character in the 6th character string (including the -)
if(keyLength<29) {
// Add a - to the end of the product key
productKey = productKey+'-';
}
break;
}
break;
}
document.getElementById(data.id).value = productKey;
}
Then a textbox like:
Code:
<input type="text" name="key" id="key" onKeyUp="productKey(this, event)" value="" size="40">
Any ideas?