-1

i am stuck in a problem...This is my code which restricts special characters but i want a logic which will restricts special characters,numerics but allow alphanumeric values... for eg:

  • valid : a1,4r,aa.
  • invalid : w@,12,@!.

    function check(e)

{

var keynum;
var keychar;
var numcheck;
if(window.event) // IE
{
    keynum = event.keyCode;
}
else if(e.which) // netscape/Firefox/opera
{
    keynum = e.which;
}

//condition for backspace(8) Key
if(keynum != 8)
{
    keychar = String.fromCharCode(keynum);
    numcheck = /[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*/;
    return numcheck.test(keychar);
}
else
{
    return true;
}

}

    User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>

3 Answers3

0

Alpha numeric validation from SO itself :

var reg_password1 = 'tes123';
var letters = /^[a-zA-Z0-9]+$/;

var result = letters.test(reg_password1);

alert(result);

See this question

Fiddle not by me

Community
  • 1
  • 1
Nishant Jani
  • 1,965
  • 8
  • 30
  • 41
0

I think this is the regex you need :

^[A-Za-z0-9]*[A-Za-z]+[A-Za-z0-9]*$

It matches zero or more alphanumeric characters followed by atleast one letter followed by zero or more alphanumeric characters.

So it allows aa and 0r

and does not allow 99 or sequence containing non-alphanumeric characters.

Your question says only alphanumeric characters are allowed. Your example says aa. should be allowed. If so, use :

^[A-Za-z0-9.]*[A-Za-z]+[A-Za-z0-9.]*$

It allows . along with at least one letter such as .aa and aa.

Check it like this :

numcheck.test(inputString);

where inputString is the input like a23, we and .aa which are matched or 12 and k@ which are not matched

numcheck is /[A-Za-z0-9.]*[A-Za-z]+[A-Za-z0-9.]*/

Naveed S
  • 5,106
  • 4
  • 34
  • 52
0

I believe this would satisfy your need.

[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*

This would restrict only numbers such as 12, 13, etc., would now allow any special character, and as required, would allow words containing alphabets and numbers both such as asd12, 12asd12, 12asd, etc.

Ali Shah Ahmed
  • 3,263
  • 3
  • 24
  • 22