0

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!

2
  • I think you don't want \- after number but only /[a-z0-9]$/; Commented Apr 19, 2014 at 14:54
  • 3
    Restricting the alphabet available for user names and passwords is a security failure. Commented Apr 19, 2014 at 14:57

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.