Search code examples
htmlcontenteditable

Is there a way to accept only specific datatype like date with contenteditable html attribute?


Is there a way to achieve something like this?

<pre>
<p contenteditable="true" type="date">12-04-1994</p>
</pre>

so it only accepts date formats?


Solution

  • This might help; note that it ignores everything after the 10th character and it doesn't check the actual date values for validity (e.g. you can say 45/96/2543 and it will be valid).

    setInterval(check,100);
    function check(){
      var date=document.getElementById("date").innerHTML;
      if(!isNaN(parseInt(date.charAt(0), 10))&&!isNaN(parseInt(date.charAt(1), 10))&&date.charAt(2)=="-"&&date.charAt(5)=="-"&&!isNaN(parseInt(date.charAt(3), 10))&&!isNaN(parseInt(date.charAt(4), 10))&&!isNaN(parseInt(date.charAt(6), 10))&&!isNaN(parseInt(date.charAt(7), 10))&&!isNaN(parseInt(date.charAt(8), 10))&&!isNaN(parseInt(date.charAt(9), 10))){
        document.getElementById("output").innerHTML="Yes Date";
      } else {
        document.getElementById("output").innerHTML="No Date";
      }
    }
    <pre>
    <p contenteditable='true' id='date' style='border:1px solid black;'>Edit me</p>
    <p id='output'></p>
    </pre>