限制 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 许可协议

阅读 482
1 个回答

android 上的 onKeyPress 事件效果不佳。

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

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

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

推荐问题