Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I validate a string (length=1)? 1

Status
Not open for further replies.

JohnnyBGoode

Programmer
May 1, 2002
76
CA
2 Parts:

(1) I would like to make sure that a string (of length 1) is within the range a-z, A-Z.

(1) I would like to make sure that a string (of length 1) is within the range 0-9.

How can these be done? Are regular expressions the way to go here?

 
In javascript:
Code:
   // see if string is a single character in range a-z, A-Z
   function isAlpha(aString) {
      return (aString.length == 1) && (aString.toUpperCase() >= &quot;A&quot;) && (aString.toUpperCase() <= &quot;Z&quot;);
   }
   // see if string is a single chracter in range 0 - 9;
   function isDigit(aString) {
      return (aString.length == 1) && (aString >= &quot;0&quot;) && (aString <= &quot;9&quot;);
   }
There are many other solutions (using [tt]indexOf()[/tt] or [tt]charCodeAt[/tt], etc.), but the above are, perhaps, the simplest.

Hope this helps.

________________________________________
[hippy]Roger J Coult; Grimsby, UK
In the game of life the dice have an odd number of sides.
 
or, if you want ppl that see your code and don't understand regular expressions to think you're a genius you could do this:
Code:
function isAlpha(str) {
   return((/^[a-zA-Z]+$/).test(str))
}
function isNumeric(str) {
   return((/^[0-9]+$/).test(str))
}

-kaht

banghead.gif
 
Thanx for you help, guys. I ended up using the >=A AND <=Z method, but I wanted to know how to use the Regular Expressions. Thanx to both of you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top