user3290356
user3290356

Reputation: 95

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 a-z characters and numbers 0-9 in the usernames. I want to use regex and 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 e.g.: apple or #apple always write "true".

What should I do?

Thanks!

Upvotes: 0

Views: 85

Answers (3)

raina77ow
raina77ow

Reputation: 106385

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);

  • 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.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

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\-]+/

Upvotes: 0

Lugia101101
Lugia101101

Reputation: 671

Your Regexp tests if the last character is within those constraints, try using /^[a-z0-9\-]+$/.

Upvotes: 1

Related Questions