Search code examples
javascriptreactjsregexantd

Regex to insert hypnonen antd input


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.


Solution

  • 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;