Reputation:
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 '/
'
/
' (Without using the input type="date"
)
UPDATE The purpose is not to use HTML5.
Upvotes: 2
Views: 16816
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
Reputation: 2105
Try this:
<input name="number" onkeyup="if (/[^\d/]/g.test(this.value)) this.value = this.value.replace(/[^\d/]/g,'')">
Upvotes: 1
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
Reputation: 11162
You can use the HTML5 input pattern attribute along with a Regular expression:
<input type="text" id="dateField" pattern="[\d/]"/>
Upvotes: 1