[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 659
  • Last Modified:

alphanumeric validation in regular expression in javascript

Hi,

alphanumeric  validation in regular expression in javascript
0
Sathish David  Kumar N
Asked:
Sathish David  Kumar N
  • 4
1 Solution
 
apresenceCommented:
The attached isAlphaNum is probably what you need.
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
  function isAlphaNum(s)
  {
    return /([a-zA-Z0-9]+)$/.test(s);
  }

  document.write('<pre>\n');

  s = "123ABC";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '<br>\n');
  s = "foo-";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '<br>\n');
  s = "bar.";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '<br>\n');
  document.write('</pre>\n');
</SCRIPT>
</HEAD>

Open in new window

0
 
apresenceCommented:
Save that to an htm/html file and look at the output:
123ABC is alphanum = true
foo- is alphanum = false
bar. is alphanum = false
0
 
apresenceCommented:
Sorry, please use the following instead.

Output:
123ABC is alphanum = true
foo- is alphanum = false
bar. is alphanum = false
.baz is alphanum = false

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
  function isAlphaNum(s)
  {
    return /^([a-zA-Z0-9]+)$/.test(s);
  }

  document.write('<pre>\n');

  s = "123ABC";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '\n');
  s = "foo-";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '\n');
  s = "bar.";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '\n');
  s = ".baz";
  document.write(s + ' is alphanum = ' + isAlphaNum(s) + '\n');
  document.write('</pre>\n');
</SCRIPT>
</HEAD>

Open in new window

0
 
Gurvinder Pal SinghCommented:
var str = "sdfsdfsdf234234aDSD";
var re = new RegExp("^[a-zA-Z0-9]+$", "g");
var myArray = re.test(str);
0
 
apresenceCommented:
dravidnsr, please be sure to use the second regular expression I provided.  The first will match strings which only end in alphanumeric chars, like:
.foo

The second one fixes this by adding "^" to the regular expression, which additionally tells the regex parser that the first character onward has to be alphanumeric.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now