Home > database >  How can I restrict a date input value?
How can I restrict a date input value?

Time:05-21

I want to display an input type date from from today to future.

I tried this:

<input type="date" id="dateAppointment" name = "dateAppointment" min="2022-05-21" placeholder="date"  required/>

But when I display it I can still select any time, it does not restrict me as I indicate. What is the problem?

If is necessary some code I work with Javascript.

CodePudding user response:

You are using the min attribute correctly. If you want to set the min value dynamically to today you have two options:

Option 1 - On the server-side.

HTML comes from a server. If a server is dynamically generating this HTML, you can insert today’s date. This is the case if you are using languages like Java, Python, PHP, or NodeJS to generate and return an HTML file.

Here is an example using PHP:

<input type="date" value="<?php echo date('Y-m-d'); ?>" />

Option 2 - On the client side

Maybe the HTML files are static HTML files, which are not generated by a server. This is the case if you are hosting a static site. In that case, you will need to use JavaScript to set the min attribute after the page has loaded.

// create a function, which returns the current date
Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

// use this function
document.getElementById('dateAppointment').value = new Date().toDateInputValue();

Caution

Both approaches are not tamper proof. A bad actor could visit your page and afterwards use their browser’s developer tools to remove or change that min attribute. This means appointments could be made in the past.

After a user makes a booking, the booking information will reach a server/service. This server needs to also validate that the appointment date it received is not in the past. If it is in the past, it should refuse to book and throw an error back to the user. — This is why you should always do server-side validation and never trust anything coming from the client-side (the browser).

CodePudding user response:

Yes indeed it is possible to make it thanks to javascript and I think that this answers detailed it perfectly : How to set input type date's default value to today? Hope this is going to help you.

  •  Tags:  
  • html
  • Related