Automatic backslash for Date Text Input React Native?

Viewed 15198

Does anyone know how to create a text input that when you start typing in it, it automatically allows for a certain amount of digits with an automatic backslash separation for the numbers.

DD / MM / YYYY (I am not looking to use a date picker or library).

3 Answers

Try this react component:

https://github.com/benhurott/react-native-masked-text

INSTALL

npm install react-native-masked-text --save

USAGE

render() {
//the type is required but options is required only for some specific types.
  return (
    <TextInputMask
      refInput={(ref) => this.myDateText = ref;}
      type={'datetime'}
      options={{
        format: 'DD-MM-YYYY HH:mm:ss'
      }}
    />
  )
}

there's one type of mask that is suitable for you:

datetime: use datetime mask with moment format (default DD/MM/YYYY HH:mm:ss). It accepts options (see later in this doc).

You could use something like this:

<TextInput
  onChangeText={(text) => this.handleTextChange({text})}
  value={this.state.text}
/>

In handleTextChange() do whatever you need to the insered text and than set it to the state

checkValue(str, max) {
    if (str.charAt(0) !== '0' || str == '00') {
      var num = parseInt(str);
      if (isNaN(num) || num <= 0 || num > max) num = 1;
      str = num > parseInt(max.toString().charAt(0))
      && num.toString().length == 1 ? '0' + num : num.toString();
    };
    return str;
  };
    this.type = 'text';
    var input = e.target.value;
    var expr = new RegExp(/\D\/$/);
    if (expr.test(input)) input = input.substr(0, input.length - 3);
    var values = input.split('/').map(function(v) {
      return v.replace(/\D/g, '')
    });
    if (values[0]) values[0] = this.checkValue(values[0], 12);
    if (values[1]) values[1] = this.checkValue(values[1], 31);
    var output = values.map(function(v, i) {
      return v.length == 2 && i < 2 ? v + '/' : v;
    });
    this.setState({
      registrationDate:output.join('').substr(0, 14)
    })
  }
<input type="text" className="input-attr" maxLength="25" onChange={(e) => this.dateTimeInputChangeHandler(e)}
                           placeholder={translationData.datePlaceholderText}
                           value={this.state.registrationDate}/>

You can implement it using something like this. onchange event will help process input.

Related