简体   繁体   English

javascript正则表达式不起作用

[英]javascript regex doesn't work

I want to create a register form. 我想创建一个注册表单。 Naturally, every user have to choose a username and a password, but I want to, that there are only small az characters and numbers 0-9 in the usernames. 当然,每个用户都必须选择用户名和密码,但我想,用户名中只有小的az字符和数字0-9。 I want to use regex and javascript. 我想使用正则表达式和JavaScript。 Here is the code: 这是代码:

<!DOCTYPE HTML>  
<html lang="en-US">  
<head>  
  <meta charset="UTF-8">  
  <title></title>  
  <script type="text/javascript">  
    function check(value) {  
      valid_qwe = /[a-z0-9\-]$/;
      trying = valid_qwe.test(value);
      alert("The name: " + value + "\nBe allowed: " + trying);  
      return valid_qwe;  
    }
  </script>  
</head>  
<body>  
  <input type="text" autofocus id="qwe" name="qwe" value="" />  
  <input type="submit" onClick="check(document.getElementById('qwe').value);" value="Check" id="check" />  
</body>  
</html>  

But when I'm trying to test eg: apple or #apple always write "true". 但是,当我试图测试例如:apple或#apple总是写“真”。

What should I do? 我该怎么办?

Thanks! 谢谢!

Should be: 应该:

var valid_qwe = /^[a-z0-9-]+$/;

Three changes here: 这里有三个变化:

  • the pattern itself now is one or more characters of the given range (note that + quantifier after the brackets); 模式本身现在是one or more characters of the given range (注意括号后面的+量词);

  • it's anchored both to the end (with $ ) and the beginning (with ^ ) of the string; 它固定在字符串的末尾(带$ )和开头(带^ );

  • no need to escape - within the character range if it's the last or the first symbol of it. 无需逃避-在角色范围内,如果它是它的最后一个或第一个符号。

Finally, I'd rather see all the variables used within that function of yours localized - hence var . 最后,我宁愿看到你本地函数中使用的所有变量本地化 - 因此var

你的Regexp测试最后一个字符是否在这些约束内,尝试使用/^[a-z0-9\\-]+$/

Your regex is correct ( except that you are checking the last character ), but you're not matching the full string. 你的正则表达式是正确的( 除了你检查最后一个字符 ),但你没有匹配完整的字符串。

Add a + to your regex, which means, match one or more of the previous token. 在正则表达式中添加一个+ ,表示匹配前一个标记中的一个或多个。

So your regex should be: 所以你的正则表达式应该是:

var valid_qwe = /[a-z0-9\-]+/

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

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