sanniassin / react-input-mask

Input masking component for React. Made with attention to UX.
MIT License
2.22k stars 258 forks source link

onComplete callback #100

Open gargantuan opened 7 years ago

gargantuan commented 7 years ago

An on complete callback would be useful. For example, if using this component as a date input, the values have no meaning until the the mask is completed. It would be convenient to not have to worry about parsing dates until we're confident that the mask has been completed.

jurassix commented 6 years ago

@gargantuan I have this need as well.

I'm working around this by doing the following. Unfortunately, isFilled is an internal API and fragile. We really need an onComplete to harden this.

import React, { Component } from 'react';
import InputMask from 'react-input-mask';
import { isFilled } from 'react-input-mask/lib/utils/string';

class Example extends Component {
  handleBlur = event => {
    if (isFilled(this.maskInput.maskOptions, this.maskInput.value)) {
      return this.props.onChange(this.maskedInput.value);
    }
  };

  render() {
    return (
      <InputMask
        ref={ref => {
          this.maskInput = ref.input;
        }}
        onBlur={this.handleBlur}
        mask={this.props.mask}
      />
    );
  }
}
jurassix commented 6 years ago

@sanniassin are you open to a PR with this new API added? Any thoughts on naming etc?

jurassix commented 6 years ago

Ideally, something like this.

import React, { Component } from 'react';
import InputMask from 'react-input-mask';

class Example extends Component {
  handleComplete = event => this.props.onChange(this.maskedInput.value);

  render() {
    return (
      <InputMask
        ref={ref => {
          this.maskInput = ref.input;
        }}
        onComplete={this.handleComplete}
        mask={this.props.mask}
      />
    );
  }
}