Javascript 使用至少一个字母表(Az)进行名称验证的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14773421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for Name validation with atleast one alpahbet(A-z)
提问by Lucky
I need a regex that should validate it should contain atleast one alphabet(A-Z,a-z) and optionally numbers(0-9).
我需要一个应该验证它应该包含至少一个字母表(AZ,az)和可选的数字(0-9)的正则表达式。
Valid names:
有效名称:
- aaaa
- aaaa1
- SO
- John P. Example
- 啊啊啊
- aaaa1
- 所以
- 约翰 P. 示例
Invalid names,
无效名称,
- 1111
- @@@@
- 1111
- @@@@
the Regex I have tried so far
到目前为止我尝试过的正则表达式
[a-zA-Z0-9\.\'\-_\s]{1,20}
and
和
function validateFirstName(a) {
if (/[0-9]/.test(a) && /[a-zA-Z]/.test(a)) {
return false;
} else {
return true;
}
}
but both doesn't work.
但两者都不起作用。
Can anyone help in this regard?
任何人都可以在这方面提供帮助吗?
回答by Steve Chambers
Try:
尝试:
^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$
To explain:
解释:
- The bit in the middle square brackets (the "meat in the sandwich") matches an alphabet character. The + after it makes sure there is at least one of these.
- The other two square-bracketed expressions (the "bread in the sandwich") match alphanumeric characters. The * after each allow any number of these.
- The ^ and $ surrounding the whole thing make sure it is the whole text being looked at and not just part of it.
- 中间方括号中的位(“三明治中的肉”)匹配一个字母字符。它后面的 + 确保至少有其中之一。
- 另外两个方括号表达式(“三明治中的面包”)匹配字母数字字符。每个后面的 * 允许任意数量的这些。
- 围绕整个内容的 ^ 和 $ 确保它是整个文本,而不仅仅是其中的一部分。
回答by Clement Herreman
[a-zA-Z]+.*|.*[a-zA-Z]+|.*[a-zA-Z]+.*match the examples you supplied.
[a-zA-Z]+.*|.*[a-zA-Z]+|.*[a-zA-Z]+.*匹配您提供的示例。
回答by fejese
So you want any number of a-z char or number, then at least one a-z char and any number of a-z char or number again:
所以你想要任意数量的 az 字符或数字,然后至少有一个 az 字符和任意数量的 az 字符或数字:
^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$
This should work fine.
这应该可以正常工作。
回答by Felix Kling
If you only want t check whether a string contains an alphabetic character, then simply do:
如果您只想检查字符串是否包含字母字符,则只需执行以下操作:
/[a-z]/i.test(str)
If the string should be composed of only alphanumeric characters with at least one alphabetic character:
如果字符串应仅由字母数字字符和至少一个字母字符组成:
/^(?=.*[a-z])[a-z\d]+$/i.test(str)
or
或者
/[a-z]/i.test(str) && /^[a-z\d]+$/i.test(str)
Otherwise, [a-zA-Z0-9.'\-_\s]{1,20}looks good to me actually, but you have to anchor it to the beginning and end of the string:
否则,[a-zA-Z0-9.'\-_\s]{1,20}实际上对我来说看起来不错,但是您必须将其锚定到字符串的开头和结尾:
/^[a-zA-Z0-9.'\-_\s]{1,20}$/.test(str)
If you want to enforce an alphabetic character, you have to include the lookahead or make an extra test, just like in the previous example.
如果要强制使用字母字符,则必须包含前瞻或进行额外测试,就像在前面的示例中一样。

