简体   繁体   English

为什么正则表达式不允许使用字母?

[英]Why the regular expression is not allowing alphabets?

I am using this to restrict user from inputting numbers. 我用这个来限制用户输入数字。 I want him to only input alphabets like a,b,c,d,e etc 我希望他只输入像a,b,c,d,e等字母

but it works oppositely. 但它的工作原理相反。

  <input type="text" id="name" name="name" oninput="this.value = this.value.replace(/[A-Za-z]*/, '');" class="form-control" placeholder="Your name" required>

使用/[0-9]/, ''

  <input type="text" id="name" name="name" oninput="this.value = this.value.replace(/[0-9]/, '');" class="form-control" placeholder="Your name" required> 

Have you tried something like 你尝试过类似的东西吗?

this.value.replace(/[^A-Za-z]*/, '')

?

I would recommend using HTML5's pattern attribute instead, and mark invalid fields using the corresponding :invalid CSS modifier. 我建议使用HTML5的pattern属性,并使用相应的:invalid CSS修饰符标记无效字段。

The difference is that the user may input numbers but won't be able to submit the form. 不同之处在于用户可能输入数字但无法提交表格。 This way he/she knows what's wrong and can fix his/her mistake. 这样他/她知道什么是错的,可以解决他/她的错误。

Demo: 演示:

 input:invalid {border: 2px solid red;} 
 <form> <input type="text" id="name" name="name" placeholder="Your name" pattern="[^\\d]+" required> <input type="submit" /> </form> 

You can also add a custom validation message: 您还可以添加自定义验证消息:

 document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('[data-invalid]').forEach(function (input) { input.addEventListener('invalid', function () { input.setCustomValidity(input.dataset.invalid); }); input.addEventListener('input', function () { input.setCustomValidity(''); }) }); }); 
 input:invalid {border: 2px solid red;} 
 <form> <input type="text" id="name" name="name" placeholder="Your name" pattern="[^\\d]+" data-invalid="Your name cannot contain numbers!" required> <input type="submit" /> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM