如何在输入字段中仅允许英文字母? [英] How to allow only English letters in input fields?

查看:73
本文介绍了如何在输入字段中仅允许英文字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我的输入字段:

So, this is my input field:

<input type={type} name={name} />

我怎么只允许英文字母?

How can I allow only English letters?

这是RegEx,我相信我应该使用:/[A-Za-z]/ig

This is the RegEx, I believe I should use: /[A-Za-z]/ig

https://regex101.com/r/upWFNy/1

我假设onChange()事件应与setState()event.target.value结合使用.

I am assuming that onChange() event should be used for this with the combination of setState() and event.target.value.

谢谢.

PS.我需要输入WHILE.

推荐答案

我会尝试使用此onChange函数:

onChange={(e) => {
  let value = e.target.value

  value = value.replace(/[^A-Za-z]/ig, '')

  this.setState({
    value,
  })
}}

请参阅codepen: https://codepen.io/bozdoz/pen/vzJgQB

See the codepen: https://codepen.io/bozdoz/pen/vzJgQB

这个想法是用^反转您的正则表达式匹配器,并用''

The idea is to reverse your regex matcher with ^ and replace all non-A-z characters with ''

这篇关于如何在输入字段中仅允许英文字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆