Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable future dates in reactjs?

I have not use any datepicker still code is working fine. I have selected input type to date and everything's working fine. Now I want to disable future dates. How do I do that?

<div className="form-group col-md-6">
                            <label for="inputDate4">Date of Birth</label>
                            <input type="date" className="form-control" id="inputDate4" placeholder="Date of Birth" name="dob" onChange={this.handleChange} />
                        </div>

Edit: Issue solve by other way

I used React Date Picker

It is so easy to implement. Just install the npm package

npm install react-datepicker --save

Install moment aslo

npm install moment --save

Import the libraries

import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

In the constructor

this.state = {
      dob: moment()
    };
    this.dateChange = this.dateChange.bind(this);

dateChange function

dateChange(date) {
    this.setState({
      dob: date
    });
  }

And finally the render function

 <DatePicker
     selected={this.state.dob}
     onChange={this.dateChange}
     className="form-control"
    placeholder="Date of Birth"
    maxDate={new Date()}
    />

Here the maxDate function is used to disable future dates.

maxDate={new Date()}

Source: https://www.npmjs.com/package/react-datepicker

Thank you!

like image 421
Karan Patokar Avatar asked Apr 16 '18 06:04

Karan Patokar


1 Answers

You can use a min, max attribute to restrict the date selection within a date range

<div className="form-group col-md-6">
     <label for="inputDate4">Date of Birth</label>
     <input type="date" className="form-control" id="inputDate4" placeholder="Date of Birth" name="dob" onChange={this.handleChange} max={moment().format("YYYY-MM-DD")}/>
</div>
like image 77
Shubham Khatri Avatar answered Oct 01 '22 16:10

Shubham Khatri