Others



Automatically add slash(/) or hyphen(-) in Date input using JavaScript


The following example shows, Automatically add slash(/) or hyphen(/) when enter date in input using JavaScript

Demo

Example
<html>
  <body>
    <label for="amount">Date</label>
    <input type="text"  id='dateFormat' placeholder='dd-mm-yyyy' />
    
    <script>
      function formatNumber(num,from,limit){
        num=Number(num)>from&&Number(num)<10&&num.length==1?"0"+num:num;
        if(Number(num)>limit){
          num=num.substr(1, 2);
          num=Number(num)>from&&Number(num)<10&&num.length==1?"0"+num:num;
        }
        return num;
      }

      dateElement=document.querySelector("#dateFormat");
      dateElement.addEventListener('input',function(){
        var dateValue = dateElement.value;
        if (/\D$/.test(dateValue)){
        dateValue = dateValue.substr(0, dateValue.length - 3);
        }
        dateValue=dateValue.replaceAll(" ","");
        var arr = dateValue.split('-');

        if(arr[0])arr[0]=formatNumber(arr[0],3,31);
        if(arr[1])arr[1]=formatNumber(arr[1],1,12);

        var  result= arr.map(function(val,index) {
        return val.length == 2 && index < 2 ? val + ' - ' : val;
        });
        dateElement.value = result.join('').substr(0, 14);
      });
      
      dateElement.addEventListener('blur',function(){
        dateElement.value=dateElement.value.replaceAll(" ","");
      });
    </script>
  </body>
</html>
Try it Yourself