skip to Main Content

I’m using ant design’s range picker
Do so to allow the entry of start and end dates that are no more than 30 days old.
For example, if I immediately select May 1, 2023, only the last date is allowed to be selected as May 30, 2023, but not June 1, 2023.

2

Answers


  1. You have to use disabledDate prop

    Here is the documentation:

    https://ant.design/components/date-picker#components-date-picker-demo-disabled

    Here is a demo with only current two weeks allowed to select

    https://codesandbox.io/s/disabled-date-time-antd-5-4-7-forked-ddl8wn?file=/demo.tsx

    Also, you can use dayjs to validate if it is 30 days, or end of the month, of other kind of validations:

    https://day.js.org/docs/en/manipulate/manipulate

    Login or Signup to reply.
  2. import {
      DatePicker
    } from "antd";
    import moment from "moment";
    
    const {
      RangePicker
    } = DatePicker;
    
    function MyDatePicker() {
      // Create a state variable for the start date
      const [start, setStart] = useState(null);
    
      return ( <
        RangePicker
        // Set the start date when a date range is selected
        onCalendarChange = {
          (dates) => setStart(dates[0])
        }
        // Disable dates that are before today or more than 30 days after the start date
        disabledDate = {
          (current) =>
          current && (current < moment().endOf('day') || (start && current > start.clone().add(30, 'days')))
        }
        // Reset the start date when the date picker is closed
        onOpenChange = {
          (open) => !open && setStart(null)
        }
        />
      );
    }
    
    export default MyDatePicker;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    In this code, we utilize a state variable named ‘start’ to maintain a reference to our start date. When a date range is selected, the function ‘onCalendarChange’ is invoked to set this start date.

    The ‘disabledDate’ function is used to restrict the date range. It prevents the selection of any dates that fall before the current day or exceed 30 days after the initial start date.

    Lastly, to ensure a reset of the selection process, the ‘onOpenChange’ function is employed. This function resets the start date to null each time the date picker is closed, providing a fresh start for each new date range selection.

    This systematic approach ensures a controlled, accurate date range selection, enhancing the overall functionality of the date picker.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search