Force a specific pattern into a textbox

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Force a specific pattern into a textbox



I have a web page with a text box on it. Currently through some javascript the text box only allows you to type numbers or a minus sign or dash - .



My question is that I would like a way to further force the input to be in the form of 3 numbers followed by a '-' then followed by 2 more numbers and that's it. So it looks like ###-## every time its entered. I've tried lots of ways so far like this code.


<input type="text" name="Item1" id = "Item1" value="" type="number" pattern="(0)3-(0)2" onkeypress="return isNumberKey(event)"/></input>



But the pattern didn't work. Any suggestions to where I should start some research or sample code would be great. I was hoping it might be achievable in CSS but javascript will do.





AFAIK, pattern won't work with type="number". FYI, you have multiple type attributes
– Phil
Aug 10 at 5:26



pattern


type="number"


type





are you looking for a Javascript implementation for this or something else?
– Himanshu Tanwar
Aug 10 at 5:32




3 Answers
3



input to be in the form of 3 numbers followed by a '-' then followed by 2 more numbers




let inputHandler = function(e)
var tmp = this.value.replace(/[^0-9]/g, '').split('');
if (3 < tmp.length)
tmp.splice(3, 0, '-');

this.value = tmp.join('').substr(0, 6);
;

document.addEventListener('DOMContentLoaded', function(e)
document.querySelectorAll('[name=Item1]').forEach(function(inp)
inp.addEventListener('input', inputHandler);
);
);


input
margin: 2px;


<input type="text" name="Item1" /><input type="text" name="Item1" /><input type="text" name="Item1" />





This is perfect but all answers were good thanks guys...This one wins because you cant type it in wrong and it adds a dash automatically..so awesome
– Jon
Aug 13 at 1:27



Following pattern should do the trick.


[0-9]3-?[0-9]2



As in


<input type="text" name="Item1" id = "Item1" value="" type="number" pattern="[0-9]3-?[0-9]2" onkeypress="return isNumberKey(event)"/></input>



The pattern you are looking for is :


[0-9]3-[0-9]2



Expanding on this,


[0-9] : accepts any value from 0 to 9
<pattern>x : specifies how many times <pattern> should be matched
[0-9]3 : match value from 0 to 9 three times




<form>
<input type="text" name="Item1" id = "Item1" value="" type="number" pattern="[0-9]3-[0-9]2">
<input type="submit">
</form>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS