【问题标题】:restrict special characters in reactNative TextInput限制反应本机 TextInput 中的特殊字符
【发布时间】:2019-05-12 01:03:20
【问题描述】:

我试图阻止我的 TextInput 获取像 $,%,^,&,(,) etc 这样的值。基本上我的 TextInput 应该只允许字母。我的方法如下。但我仍然可以输入这些其他字符。如何防止 TextInput 中的特殊字符

restrict(event) {
        const regex = new RegExp("^[a-zA-Z]+$");
        const key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }

                         <TextInput
                                underlineColorAndroid='transparent'
                                allowFontScaling={false}
                                style={styles.questionText}
                                onKeyPress={e => this.restrict(e)}
                                value={firstNameState}
                            />

【问题讨论】:

  • 如何检测特殊字符?
  • 试试regex = /^[^!-\/:-@\[-`{-~]+$/;
  • @WiktorStribiżew 谢谢它的工作。但有一个问题,特殊字符只有在我输入字符后才会被删除。因此,如果我在开始时输入了一个特殊字符,之后没有输入任何内容,我最终会在我的 TextInput 中输入一个特殊字符。我该如何处理?
  • 我不知道为什么会这样。如果它仍然与正则表达式而不是代码有关,请尝试/^[^!-\/:-@\[-`{-~]*$/
  • 你解决了吗

标签: javascript regex reactjs react-native


【解决方案1】:

android 上的 onKeyPress 事件不能很好地工作。

这就是为什么我选择使用一种方法来消除这些字符,然后将其保存在您想要的任何位置,就像它可能会改变您的字段状态一样。

restrict = text => text.replace(/[`~0-9!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')

【讨论】:

  • 这应该不起作用,除非你从这个表达式末尾的“gi”中删除“i”
【解决方案2】:

您可以使用您的正则表达式定义您的 OnChange 事件处理程序,您将在其中检查输入字符串是否与您的正则表达式匹配 /^[a-zA-Z]+$/.test(text)

const {useState} = React;

const App = () => {
  const [value, setValue] = useState("");
  const onChange = e => {
    const input = e.currentTarget.value;
    if (/^[a-zA-Z]+$/.test(input) || input === "") {
      setValue(input);
    }
  };
  return (
    <div className="App">
      <input
        value={value}
        onChange={onChange}
        underlineColorAndroid='transparent'
        allowFontScaling={false}
      />
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

【讨论】:

    【解决方案3】:

    我必须通过这行代码来屏蔽特殊字符。

    var 格式 = /[!@#$%^&*()_+-=[]{};':"\|,./?]+/;

    if(format.test(string)){ }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      相关资源
      最近更新 更多