0

I have a Laravel app with a date field.

When I use "type=text"

<input type="date" class="form-control" id="startdate" placeholder="Start date" name="startdate" />

I get the value that is stored in my database.

When I use "type=date"

<input type="date" class="form-control" id="startdate" placeholder="Start date" name="startdate" />

I get dd/mm/yyyy and a dropdown (datepicker) to select a number for each of these. I would have expected that the dd, mm and yyyy would be pre-filled with the date from my database.

While input=text is working, I don't like that as the uses can then type in any text in that field.

What is the best way to do this? Keep the input=date and fix that or put it to input=text and do server side validation?

wiwa1978
  • 2,317
  • 3
  • 31
  • 67
  • 1
    why would you expect the date field to be pre-filled with anything from your db? You have no `value` to set that initial date. – Marc B Jul 07 '16 at 15:49
  • One should always perform server side validation, since the manipulation of html fields is very easy. The best way I can come up with is using a UI for picking dates, either HTML 5 (type=date) or a jQuery datepicker plug-in. Post submitting you should validate the input value, server side. The advantage of jQuery datepicker is you can choose the input format, resulting in easy validation. – Jan Willem Jul 07 '16 at 15:51
  • @MarcB Correct, I'm using Javascript $('#edit-auction-modal ').find('input#startdate').val(formattedStartDate) to set that input field. It works for other non-date fields. – wiwa1978 Jul 07 '16 at 15:56
  • Make sure you are setting it with a `YYYY-MM-DD` format: http://stackoverflow.com/questions/14212527/how-to-set-default-value-to-the-inputtype-date – Jeremy Harris Jul 07 '16 at 15:57

1 Answers1

0

Try this

function getDefaultDate(curDate){
var dt = new Date(curDate);
var date = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
if (month.toString().length == 1) {
    month = "0" + month
}
if (date.toString().length == 1) {
    date = "0" + date
}
return year.toString() + "-" + month.toString() + "-" + date.toString();
}

var fdate = getDefaultDate(curDate); // pass db date

document.getElementById("startdate").value = fdate;
Shahbaz Hashmi
  • 2,631
  • 2
  • 26
  • 49