Reputation:
I need to make sure that a certain field only takes numbers as after some default alphabetic characters Like XXX-XX-1234. Here XXX-XX- are default characters which shouldn't be removed. After these alphabets I want the user to be unable to type in any characters other than numbers.
Is there a neat way to achieve this?
Upvotes: 3
Views: 200
Reputation: 1612
Here is a FIDDLE
I wish I could have made this a comment on @scaisEdge 's answer because I just built off of it to add a little more helpful stuff but it is just too much to fit in a comment:
HTML:
<form>
<button>submit</button>
<input type="text" name="name1" value="ABC-DE-" pattern="[A-Za-z]{3}-[A-Za-z]{2}-\d{4}$" title="LLL-LL-DDDD - L is any letter, D is any digit" />
<input type="text" name="name2" value="XXX-XX-" pattern="XXX-XX-\d{4}$" title="XXX-XX-DDDD - D is any digit, rest as is" />
</form>
I used his answer as a base, then did the following to illustrate more:
What not to do
I spent a lot of time "rolling my own" code to make a version of a text input that specifically limited all actions on it up front (on input change, keydown, keyup, mouse click) to only allow putting in the last 4 digits and nothing else. It became a game of "chase the corner cases" and I quickly became convinced that using a plugin or library that is thoroughly vetted by the developer community is the way to go for such an endeavor, or using the pattern attribute as discussed above.
Not only was it "vertically oriented" toward this specific pattern, I failed even after much time to iron out all the corner cases and it remained broken.
I even gave an explanation of these difficulties and put up the code and my FIDDLE in this answer, but realized that putting up broken code is just not a good idea on StackOverflow so I made the appropriate edits just now to redo this explanation and get rid of the FIDDLE and code for the alternate route I tried.
Upvotes: 1
Reputation: 133360
You can do with input regex pattern too
<input type="text" name="my_name"
pattern="[A-Za-z]{3}-[A-Za-z]{3}-[A-Za-z]{3}-[0-9]{4}" title="my title">
in your case (removing the number)
<input type="text" name="my_name" value="ABC-DE"
pattern="[A-Za-z]{3}-[A-Za-z]{2}-" title="my title">
Upvotes: 1