skip to Main Content

I would like to share with you a problem I was having while using the DatePicker component from Ant Design – React.

The first challenge was to add a mask to the manually entered date in the input field.

The second challenge was to accept changes in the input without having to press the date confirmation button.

2

Answers


  1. Chosen as BEST ANSWER

    Both issues were resolved as follows:

    public/index.html

    <!-- jquery -->
    <script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>
    
    <!-- jquery-mask -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>
    
    <!-- mask formatter -->
    <script>
      jQuery(function($){
        $('form').on('DOMSubtreeModified', function(){
          $('.ant-picker-input').find('input').attr('maxlength', '10').mask('99/99/9999');
        });
    
        $('.ant-picker-input').find('input').attr('maxlength', '10').mask('99/99/9999');
      });
    </script>
    

    And finally:

    <Form.Item
      label="Data de nascimento"
      name="birthDate">
         <DatePicker style={{width: '100%'}} format="DD/MM/YYYY" onBlur={(date) =>{
         const currentFormInitialValues = form.getFieldsValue();                                      
         currentFormInitialValues.birthDate = dayjs(date.target.value, 'DD/MM/YYYY');
                                                
         if(!date.target.value || date.target.value === ''){
            return
         }else{                                              
            form.setFieldsValue(currentFormInitialValues);
         };
     }}/>
    </Form.Item>
    

    It may not be the best way to solve the problem, but it worked. I'm open to suggestions if anyone has a better idea of how to do it.


  2. Just create an array of accepted date formats

    const dateFormatList = [
      'DD/MM/YYYY',
      'DD/MM/YY',
      'DD-MM-YYYY',
      'DD-MM-YY',
      'DDMMYYYY',
      'DDMMYY'
    ]
    

    And assign it to DatePicker format:

    <DatePicker
      mode={ 'date' }
      format={ dateFormatList }
    />
    

    Now if you type only numbers in your date field and press enter the date will be formated to the first format available in your array.

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