I am posting this question with my answer so far but would like to invite other solutions as I am not 100% sure about mine.
It will:
- Automatically place the dashes in the right place so the user only has to enter the digits.
- Can be any size. You can set a maxlength attribute on your input and it will continue to apply dashes intil it runs out of space. It will default to 8 characters max
- Allowsuser to delete digits without the need to delete the dashes too.
Why am I posting a this? I could not find the answer myself on StackOverflow and when you search this question on Google, it keeps returning a PHP answer for StackOverflow instead! There are even answers in there for Javascript. Hopefully this question can produce other solutions too!
How does it work?
This is designed to work with a real-time input.
- It works out the maximum length
- It captures the event and works out if the delete key was pressed
- The 'regex' part is saying to replace ever 2nd character with itself plus a dash.
- The next line first replaces anything that's not a number, then uses the regex to inject dashes and finally the string is sliced to remove any trailing slash
You would apply this function to your onkeyup or onpaste events, passing 'this' in.
function checkSortCode(el,ev){
var len = el.maxLength || 8;
ev = ev || window.event;
if(ev.keyCode == 8 && el.value.slice(-1) == "-"){
el.value = el.value.slice(0,-1);
} else {
var regex = new RegExp("(\\S{" + (2 - 1) + "}\\S)", "g");
el.value = el.value.replace(/[^0-9]/g,"").replace(regex,("$1"+"-")).slice(0,len);
}
}
.sortcode::placeholder{color:#eeeeee;}
body{font-family:arial,sans-serif;font-size:1.4em;}
input{font-size:1.4em;}
<label>Sort Code</label><br>
<input type="text" name="sortcode" onkeyup="checkSortCode(this,event)" onpaste="checkSortCode(this,event)" class="sortcode" size="8" maxlength="8" placeholder="00-00-00" />
Ideally, I wanted it to show the 00-00-00 format all the time and then the user would fill it in but have padded zeros where they hadn't. That's not easy as the cursor wants to go to the end of the input.