dream001
dream001

Reputation: 123

Insert auto-slash for date in mm/dd/yyyy format for "react-datepicker"

I am using react-datepicker in my project. The required format is mm/dd/yyyy. What I want is ,if I want to type a date it,should be in date format.

Eg: I want the date 21st Jan 1980. When I pick from the datepicker it is in the correct format(01/21/1980).

Now if I type the same date it's not auto inserting slash in between ,but showing the date like 01211980.

<div className="dashboard-patients-details_row_value">
   <Field name="DateRec" component={Datepicker} disabled={isEditing?false:true}/>
</div>

<div className="datepicker">
   <DatePicker
      selected={value ? moment(value) : null}
      onChange={onChange}
      disabled={disabled}
    />
  <div className="calendar-block">
    <CalendarIcon onClick={this.datepicker}
  />
 </div>
</div>

How to solve this issue?

Upvotes: 3

Views: 9393

Answers (2)

dream001
dream001

Reputation: 123

I solved the issue. This is my code

    import MaskedInput from 'react-text-mask'
import createAutoCorrectedDatePipe from 'text-mask-addons/dist/createAutoCorrectedDatePipe'

const autoCorrectedDatePipe = createAutoCorrectedDatePipe('mm/dd/yyyy HH:MM')
<DatePicker
                    selected={value ? moment(value) : null}
                    onChange={onChange}
                    disabled={disabled}
                    customInput={
                        <MaskedInput
                            pipe={autoCorrectedDatePipe}
                            mask={[/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/]}
                            keepCharPositions= {true}
                            guide = {true}
                        />

                    }
                />

Upvotes: 5

Mahendra Pratap
Mahendra Pratap

Reputation: 3653

In that case, we need to customize this tag little bit using customInput for example-

<DatePicker
  customInput={<ExampleCustomInput />}
  selected={value ? moment(value) : null}
  disabled={disabled}
   onChange={onChange}
/>

Note - change tag with your tag you can use https://github.com/text-mask/text-mask/tree/master/react/#readme library to mask your input, something Like -

<DatePicker
  customInput={<MaskedInput
  mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
/>}
  selected={value ? moment(value) : null}
  disabled={disabled}
   onChange={onChange}
/>

change the format as you want All the best.

Upvotes: 3

Related Questions