0

In my application, I have an antd input. I need to put here some type of mask like 123-456-789-123. So I'm trying to use Regex. But nothing works for me.

Here is live example https://codesandbox.io/s/basic-antd-5-8-3-forked-ds885j?file=/demo.js:0-543

And here is the code:

import React, { useState } from "react";
import "./index.css";
import { InputNumber } from "antd";

const App = () => {
    const [value, setValue] = useState(1);
    const onChange = (value) => {
        const parsedValue = value
        .toString()
        .replace(/^([0-9]{3})([0-9]{3})([0-9]{3})([0-9])$/, "$1-$2-$3-$4");
        
        // const parsedValue = value.toString().replace(/(.{3})/g, "$1-");
        console.log(parsedValue);
        setValue(parsedValue);
    };
    return <InputNumber value={value} onChange={onChange} />;
};

export default App;

.replace(/^([0-9]{3})([0-9]{3})([0-9]{3})([0-9])$/, "$1-$2-$3-$4"); this expression works fine, but only after 10 symbols are written in the input. But I want to find a solution to insert hypnonen immediately.

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
Натик
  • 13
  • 4
  • Does this answer your question? [How to change Phone number format in input as you type?](https://stackoverflow.com/questions/17980061/how-to-change-phone-number-format-in-input-as-you-type) – InSync Aug 11 '23 at 22:17
  • See also [ReactJS: mask input](https://stackoverflow.com/q/43237056). – InSync Aug 11 '23 at 23:17
  • If you insist on using regex instead of using a third-party library, [`(?<=^(?:\d{3}-?)+)(?<!-)(?!-)(?!$)`](https://regex101.com/r/zx0yPD/1) might do what you want. However, I make no guarantee that it can handle every and any case. – InSync Aug 11 '23 at 23:19

1 Answers1

0

Check the following example

I am assuming the following:

  • The length of the input should exceed 15 characters.

  • The input is always in the format 123-456-789-123.

MaskedInput.jsx

import React, { useState } from 'react';
import { Input } from 'antd';

const MaskedInput = () => {
  const [maskedValue, setMaskedValue] = useState('');

  const handleInputChange = (e) => {
    const input = e.target.value;
    // Remove non-numeric characters from the input
    const numericOnly = input.replace(/[^\d]/g, '');

    // If the numeric input is longer than 12 characters, truncate it
    const truncated = numericOnly.slice(0, 12);

    // Split the truncated numeric string into chunks of 3 characters each
    const chunks = truncated.match(/.{1,3}/g);

    // Apply the desired mask by joining chunks with hyphens
    const masked = chunks ? chunks.join('-') : '';
    setMaskedValue(masked);
  };

  return (
    <Input
      value={maskedValue}
      onChange={handleInputChange}
      placeholder="Enter value"
    />
  );
};

export default MaskedInput;
Ved
  • 938
  • 2
  • 5
  • 19