12

Been playing around with JavaScript, and what Im trying to do is only allow certain characters in the pass word field - a-z, A-Z and 0-9.

<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
  User Name:<br />
  <input type="text" name="userName" size="25" /><br />
  Password:<br />
  <input type="password" name="pw" size="25" /><br />
  <input type="submit" value="Log In" onClick="validate()"/> 
</form>

Above is my HTML, and Below is my JavaScript I tried to use to validate it - but it doesnt work - any clues.

<script language="javascript">
   document.logOn.onsubmit=validate;

   function validate(){

var name=document.logOn.pw.value;
    if(!name = "[a-zA-Z0-9]"){              
alert("Your Password Cant Have Any Funky Things In It - Play It Straight!");
    return false;
}               

    return true;
}
</script>

But This isnt working. I can still put chars in like "*" and "[" and "{" etc.

Any Thoughts?

Jason
  • 399
  • 3
  • 6
  • 11

3 Answers3

26

You need to make your condition test a regexp, not a string:

if(!/^[a-zA-Z0-9]+$/.test(name)){ ...

meaning:

  • ^ -- start of line
  • [a-zA-Z0-9]+ -- one or more characters/numbers
  • $ -- end of line

or you could search for the inverse of that, which is "any non-accepted character":

if(/[^a-zA-Z0-9]/.test(name)){
  • can you post a running fiddle example...i replaced the if block with the above code and its not working.. – Lucky Jan 02 '13 at 06:35
  • This question is 18 months old. If you're having problems, post a new question. –  Jan 03 '13 at 01:07
4
if (name.match(/[\W_]/)) { //...

Meaning if the "name" string has any character which is a non-alphanumeric or an underscore then execute the block. Note that we have to separately check for underscore (_) because the alphanumeric character class (\w) includes the underscore (so the negative class (\W) does not).

maerics
  • 151,642
  • 46
  • 269
  • 291
0

The below solution will accept only the alpha numeric value and some special key like backspace, delete etc.

If you want to add some other key then add to the array .

If you want to add some special symbol add to the same array or create a new array and compare it on the function like ex: yourNewVariableName.indexOf(e.keyCode)

var specialKeys = [8, 9, 46, 36, 35, 37, 39];
        function IsAlphaNumeric(e) {
            var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
            var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
            return ret;
        }
Alphanumeric value:
<input type="text" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;" onpaste="return false;" />
Community
  • 1
  • 1
Srikrushna
  • 4,366
  • 2
  • 39
  • 46