javascript 如何在javascript中验证至少包含一个字母和一个数字的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7075254/
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
How to validate a string which contains at least one letter and one digit in javascript?
提问by Sahal
It doesn't matter how many letters and digits, but string should contain both.
有多少字母和数字并不重要,但字符串应该包含两者。
Jquery function $('#sample1').alphanumeric()
will validate given string is alphanumeric or not. I, however, want to validate that it contains both.
Jquery 函数$('#sample1').alphanumeric()
将验证给定的字符串是否为字母数字。但是,我想验证它是否包含两者。
回答by user123444555621
So you want to check two conditions. While you could use one complicated regular expression, it's better to use two of them:
所以你要检查两个条件。虽然您可以使用一个复杂的正则表达式,但最好使用其中的两个:
if (/\d/.test(string) && /[a-zA-Z]/.test(string)) {
This makes your program more readable and may even perform slightly better (not sure about that though).
这使您的程序更具可读性,甚至可能执行得更好(虽然不确定)。
回答by symcbean
/([0-9].*[a-z])|([a-z].*[0-9])/
回答by James Gaunt
This is the regex you need
这是您需要的正则表达式
^\w*(?=\w*\d)(?=\w*[A-Za-z])\w*$
and this link explains how you'd use it
这个链接解释了你将如何使用它
回答by Drake
You can use regular expressions
您可以使用正则表达式
/^[A-z0-9]+$/g //defines captial a-z and lowercase a-z then numbers 0 through nine
function isAlphaNum(s){ // this function tests it
p = /^[A-z0-9]+$/g;
return p.test(s);
}