1

I've decided to use a textbox for getting the users date of birth, I'm trying to make this textbox so it restricts the users input into DD/MM/YYYY, What i'm trying to get is to that the slash(/) is fixed within the textbox. The user won't want to have the type the "/" so I'm trying to get it fixed in the textbox

This is what I'm trying to achieve


|____/____/___|

my code so far is just a basic textbox but here it is anyway

<label for="title">Date of Birth</label>
<input type="text" name="dateofbirth" id="dateofbirth">
</div>
TF120
  • 297
  • 1
  • 3
  • 14

4 Answers4

7

With HTML5 you could simply use the date input type:

<input type="date" name="dateofbirth" id="dateofbirth">

Here's the MDN reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Ananth Rao
  • 1,232
  • 1
  • 9
  • 19
  • It seems a little finicky with the year, it's interesting – Derek Apr 11 '17 at 19:58
  • This is what I'm looking for, my only concern is that on firefox this doesn't seem to work, I'm not sure if this is on my end or just not firefox supported. Thanks anyway – TF120 Apr 11 '17 at 20:04
  • Not supported in FF. – Jef Apr 11 '17 at 20:06
  • @TF120 There are plenty of polyfills available. This one looks pretty good: https://github.com/brianblakely/nodep-date-input-polyfill Using the native `date` type with a polyfill is probably the most accessible solution across devices and locales. – Jordan Running Apr 12 '17 at 14:52
2

I think this is what you're looking for:

How to do date masking using javascript (without JQuery)?

If you check the Pratik Shah answer there's the format you were looking for and it seems to work.

Code:

<input
    type="text"
    name="date"
    placeholder="dd/mm/yyyy"
    onkeyup="
        var v = this.value;
        if (v.match(/^\d{2}$/) !== null) {
            this.value = v + '/';
        } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
            this.value = v + '/';
       }"
    maxlength="10"
>

It works on my Firefox 52.0.2

Hope it helps.

Community
  • 1
  • 1
FFdeveloper
  • 241
  • 3
  • 14
  • This is ideal since it works on all browsers, Thanks! – TF120 Apr 12 '17 at 15:28
  • Note that this doesn't work when trying to backspace. What you can do for this is add `!== null && backspaceTriggered` to the end of each `if` statement. Then add an `else` which simple sets `this.value = v` – James111 Aug 28 '17 at 05:04
  • It'd be really cool if this could also ignore when the user manually types the slashes (`/`). – ryvantage Jan 30 '19 at 21:00
0

This may be what you're looking for.

<input type="date" name="dateofbirth" id="dateofbirth">

Bear in mind that this won't work in certain browsers -- Firefox and older IE versions.

Jef
  • 320
  • 5
  • 14
0

You can try maskedInput plugin for jQuery. It is basically what you are looking for. https://github.com/digitalBush/jquery.maskedinput

serdar.sanri
  • 2,217
  • 1
  • 17
  • 21