user6792756
user6792756

Reputation:

Date input field DD/MM/YYYY with input type text

I am trying to make a date input but without using the date-format option of HTML5.

So let's say that my input is

<input type="text" id="dateField" />

Allowed characters only numbers and '/'

Is there any way to make this field accept only numbers and '/' (Without using the input type="date")

UPDATE The purpose is not to use HTML5.

Upvotes: 2

Views: 16816

Answers (5)

user6063698
user6063698

Reputation:

Use HTML5 date input:

<input type="date" /> 

Upvotes: 0

Eaten by a Grue
Eaten by a Grue

Reputation: 22931

You can try something like this to limit allowed characters in an input field. You'll need to dig a bit deeper to restrict the actual format.

$('#date').on('input', function() {
  this.value = this.value.replace(/[^0-9/]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="date" maxlength="10" />

You might also want to consider using a datepicker plugin (like jQuery UI Datepicker or similar)

Upvotes: 0

Ish
Ish

Reputation: 2105

Try this:

<input name="number" onkeyup="if (/[^\d/]/g.test(this.value)) this.value = this.value.replace(/[^\d/]/g,'')">

Upvotes: 1

eltonkamami
eltonkamami

Reputation: 5190

You can use an input pattern supported in IE 11+

<input type="text" pattern="\d{2}\/\d{2}\/\d{4}" />

If that still is not an option you should go for a javascript solution hooking to the change of the value of the field

var pattern = /\d{2}\/\d{2}\/\d{4}/;
document.querySelector("input").addEventListener("keyup", function(ev){
  var value = ev.target.value;
  if(!pattern.test(value){
    //value of the field is not the one you are looking for
    // handle this
  }
})

Upvotes: 0

Daniel
Daniel

Reputation: 11162

You can use the HTML5 input pattern attribute along with a Regular expression:

<input type="text" id="dateField" pattern="[\d/]"/>

Upvotes: 1

Related Questions