Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add input mask to React DatePicker

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.

like image 294
DaRoGa Avatar asked Aug 15 '18 11:08

DaRoGa


2 Answers

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.

like image 79
Aleksandr Shevelev Avatar answered Nov 15 '22 04:11

Aleksandr Shevelev


    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" />
        }
      />
    );
  }
}
like image 38
ShowPot Avatar answered Nov 15 '22 04:11

ShowPot