Search code examples
formsantd

Antd Forms: Set min value of field dynamically


I got a form using antd (5.x) forms. When a certain condition is met, I want to dynamically restrict the min value of a date field.

I know there are so-called FormInstance methods in antd. E.g. this one which sets the value of a field dynamically:

form.setFieldValue('birth_date', '2020-01-01')

Is there sth similar for setting the props of the form item dynamically? Something like form.setPropValue('birth_date', {min: '2000-01-01'}?


Solution

  • this example is from Ant Design official documentation.

    import React from 'react';
    import { DatePicker } from 'antd';
    import dayjs from 'dayjs';
    import customParseFormat from 'dayjs/plugin/customParseFormat';
    
    dayjs.extend(customParseFormat);
    
    const dateFormat = 'YYYY-MM-DD';
    
    const App: React.FC = () => (
      <DatePicker
        defaultValue={dayjs('2019-09-03', dateFormat)}
        minDate={dayjs('2019-08-01', dateFormat)}
        maxDate={dayjs('2020-10-31', dateFormat)}
      />
    );
    
    export default App;
    

    If we consider the code above, we could store the minDate and or maxDate into its own useState (or even redux state).

    That way you could dynamically control the date-range from which the user can select the date.

    Note, the component can be integrated within the form so you can use that.

    Note, this code is in TypeScript, in case you want it in JS, you can select from (II.) as shown in the img below. enter image description here