[英]How do I restrict a string to not allow numbers or special characters?
I have textbox called goalName. 我有一个名为goalName的文本框。 In goalName I want to disallow special characters and numbers.
在goalName中,我要禁止使用特殊字符和数字。 I am currently trying the following:
我目前正在尝试以下方法:
var goalNameValidation = /^[_\W\s]*$/;
if (goalName == "" || goalNameValidation.test(goalName) == true) {
//Give Error
error = true;
}
This only limits special characters, and not numbers. 这仅限制特殊字符,而不限制数字。 How would I go about restricting both?
我将如何限制两者?
I can use jQuery for this solution if that is helpful, however vanilla JavaScript would suffice. 如果有帮助,我可以将jQuery用于此解决方案,但是可以使用普通JavaScript。
It is probably easier (and more intuitive) to write a regex that matches what you WANT to allow. 编写与您希望允许的匹配的正则表达式可能更容易(更直观)。
var goalNameValidation = /^[A-Za-z]+$/;
if (goalName == "" || goalNameValidation.test(goalName) == false) {
//Give Error
error = true;
}
This way, you can look at it, and see more easily what characters are allowed/not allowed. 这样,您可以查看它,并更轻松地查看允许/不允许使用哪些字符。
将正则表达式更改为:
var goalNameValidation = /^[^a-z]*$/i;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.