SoFunction
Updated on 2025-04-07

React restricts the input of Chinese methods

Method 1:

Use the replace method and regular expression /[^\u4e00-\u9fa5]/g to filter out non-Chinese characters in the input string. Then perform regular verification of the filtered characters, and update the status value if it meets the requirements.

import React, { useState, useEffect } from 'react';
import { Input } from 'antd';
const ChineseInput = () => {
  const [value, setValue] = useState('');
  const handleInputChange = e => {
    const reg = /[\u4e00-\u9fa5]/g; // Only Chinese characters are allowed    const inputValue = (/[^\u4e00-\u9fa5]/g, ''); // Filter out input non-Chinese characters    if ((inputValue)) {
      setValue(inputValue);
    }
    else{
      setValue('');
    }
  };
  return <Input value={value} onChange={handleInputChange} />;
};
export default ChineseInput;

Method 2:

Separate the value of the value attribute from the actual input value

A new state called displayValue has been added to control the display value of the input box. In the handleInputChange method, the actual value of the input box is assigned to the value state, and it is also assigned to the displayValue state. If the input value does not meet the requirements, it will be replaced by using , so that the user can see the actual input value that is not filtered.

In addition, a new method called handleInputBlur is implemented. This method is triggered when the input box loses focus, updating the value of displayValue to the correct value state value.

import React, { useState } from 'react';
import { Input } from 'antd';
const ChineseInput = () => {
  const [value, setValue] = useState('');
  const [displayValue, setDisplayValue] = useState('');
  const handleInputChange = e => {
    const reg = /[\u4e00-\u9fa5]/g;
    const inputValue = (/[^\u4e00-\u9fa5]/g, '');
    if ((inputValue)) {
      setValue(inputValue);
      setDisplayValue(inputValue);
    } else {
      setDisplayValue();
    }
  };
  const handleInputBlur = () => {
    setDisplayValue(value);
  };
  return <Input value={displayValue} onChange={handleInputChange} onBlur={handleInputBlur} />;
};
export default ChineseInput;

Disadvantages: Both methods above have disadvantages. After entering Chinese for the second time, the previous one will be deleted.

The above is the detailed content of the Chinese way of restricting the input of antd text box in react. For more information about the input restrictions of react antd text box, please pay attention to my other related articles!