限制 reactNative TextInput 中的特殊字符

新手上路,请多包涵

我试图阻止我的 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}
                            />

原文由 CraZyDroiD 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
1 个回答

android 上的 onKeyPress 事件效果不佳。

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

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

原文由 Jesus David Diaz Diaz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题