The Web Blinders logo

Programming

How to do input masking for various HTML Date type inputs?

Inputs like Date of birth, card expiry date, publication year etc require modified date value which unfortunately browsers won't be providing,so you will see how to do in this article.
Demo of Date input masking
Demo of Date input masking

This is an use case of imaskjs and you can download full code here and for live demo here

Download imaskjs from here or use cdn as mentioned here and add it to your page

                            
<script src="path/to/imask.js"></script> 
<!-- Eg : <script src="./js/imask.js"></script> -->
<!-- OR <script src="https://unpkg.com/imask"></script> ---> 

After that create dateformat.js file and paste below code.

                            
var inputElements = document.querySelectorAll("input[data-format]");
inputElements.forEach(input => {
	let m = new IMask(input, {
		mask: input.getAttribute("data-format")
	});
});

Add dateformat.js to your webpage.

                            
<script src="path/to/dateformat.js"></script> 

How to do DD-MM-YYYY input masking?

Add data-format attribute to the input element and set it's value as 00-00-0000 like below.

                            
<input data-format="00-00-0000" type="text" placeholder="DD-MM-YYYY">

If you run your web page , you will the input getting masked.

How to do YYYY-MM-DD input masking?

Add data-format attribute to the input element and set it's value as 0000-00-00 like below.That's it.

                            
<input data-format="0000-00-00" type="text" placeholder="YYYY-MM-DD">

How to do YYYY-MM input masking?

Add data-format attribute to the input element and set it's value as 0000-00 like below.That's it.

                            
<input data-format="0000-00" type="text" placeholder="YYYY-MM">

How to do MM-DD-YYYY input masking?

Add data-format attribute to the input element and set it's value as 00-00-0000 like below.That's it.

                            
<input data-format="00-00-0000" type="text" placeholder="MM-DD-YYYY">

How to do YYYY input masking?

Add data-format attribute to the input element and set it's value as 0000 like below.That's it.

                            
<input data-format="0000" type="text" placeholder="YYYY">

Live demo https://www.thewebblinders.in/demos/various-date-types-input-masking/

Github Repo https://github.com/thewebblinders/html-input-masking

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES