I would like to implement a mask for a text input
field which accepts a date. The masked value should display directly inside of the input
.
Something like this:
<input type='text' value='____/__/__'>
I wrote the mask as a value in that example, but my intent is to allow people to write a date without typing /
or -
to separate months, years and days. The user should be able to enter numbers into the displayed field, while the mask enforces the format automatically as the user types.
I have seen this behavior on other sites, but I have no idea how it works or how to implement it myself.
After reading all post, I did my own implementation, I hope to help to someone:
The idea is,
Improvements are welcome.
Use this code:-
Input masks can be implemented using a combination of the
keyup
event, and theHTMLInputElement
value
,selectionStart
, andselectionEnd
properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:(View in JSFiddle)
There are also a number of libraries out there which perform this function. Some examples include:
You can achieve this also by using JavaScripts's native method. Its pretty simple and doesn't require any extra library to import.
You can also try my implementation, which doesn't have delay after each key press when typing the contents, and has full support for backspace and delete.
You can try it online: https://jsfiddle.net/qmyo6a1h/1/