Add input mask to React DatePicker
Asked Answered
L

2

7

I have had a google and cant seem to find what I am looking for.

I need a React Datepicker that allows the use of an input mask and the input mask stays in place as you override it number by number ie. dd/MM/yyyy or //____ turns to 01/0M/yyyy or 01/0_/____. Ideally the first option where it specifies which item goes in which field.

I have tried a few different components but failed.

The component I am currently using is react-datepicker however this doesnt seem to be able to do it. Any advice or workarounds would be appreciated.

Leboff answered 15/8, 2018 at 11:5 Comment(0)
K
10

We had a similar problem while using react-datepicker library, for a masked input you can use customInput property as described in react-datepicker documenentation. As a masked input for datepicker we used an input created with react-text-mask library. So we got code like this as the result:

import React from "react";
import Calendar from "react-datepicker";
import MaskedTextInput from "react-text-mask";

const DatePicker = props => (
   <Calendar
     customInput={
       <MaskedTextInput
         type="text"
         mask={[/\d/, /\d/, ".", /\d/, /\d/, ".", /\d/, /\d/, /\d/, /\d/]}
       />
     }
   />
);

This results into datepicker with custom input with enforsed mask __.__.___, replacing /\d/ with exact values (as dots in example above) you will get a prefilled mask. For datepicker to correctly interact with user we also added onChange handler to masked input with date validation.

Kelseykelsi answered 15/8, 2018 at 12:9 Comment(2)
Thats awesome thanks!!! thats nearly perfect for what I need!!! Do you know if theres a way to display the mask as dd/MM/yyyy instead of __/__/____ and also if theres a way to display mask on focus rather than when they enter the first value?Leboff
I believe you can customize react-text-mask to do that, or replace it with more suitable masked input component ( react-maskedinput does similar thing)Kelseykelsi
H
1
    import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import MaskedInput from 'react-maskedinput';
import moment from 'moment';

export default class DateField extends Component {
  constructor(props) {
    super(props);

    this.state = { value: '' }
  }

  updateDate(value) {
    let fieldValue = moment(value).isValid() ?
      moment(value).format('MM/DD/YYYY') :
      value;
    this.setState({ value: fieldValue })
  }

  render() {
    const { value } = this.state;
    return (
      <DatePicker
        value={value}
        onChange={value => this.updateDate(value)}          
        type="text"
        dateFormat="MM/DD/YYYY"
        customInput={
          <MaskedInput mask="11/11/1111" placeholder="mm/dd/yyyy" />
        }
      />
    );
  }
}
Heeheebiejeebies answered 15/6, 2020 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.