Checking For Invalid Characters

  • Thread starter Thread starter Darin Browne
  • Start date Start date
D

Darin Browne

Is there anything built into .NET Framework I could use
to check if a string only has numerics and alphanumerics
in it? If anything else but a numeric or alpha has been
entered I want it to error.

Thanks.
 
Darin,

You can cycle through all of the characters in the string, and then
check to see if the character is valid. You can do something like this:

// Assuming pchrChar is the character.
bool pblnAlphaNumeric = ('A' <= pchrChar && pchrChar <= 'Z') || ('a' <=
pchrChar && pchrChar <= 'z') || ('0' <= pchrChar && pchrChar <= '9');

Hope this helps.
 
You can use the Parse method of the numeric types.

float realNumData = 0;
try
{
realNumData = float.Parse(<textToParse>);
}
//The string could not be parsed into a number
catch (FormatException)
{
this.statusBar1.Text = "Invalid real number";
}
//The number is out of range of the float type
catch (OverflowException)
{
this.statusBar1.Text = "Number out of range";
}
 
Hi,

You could also use a regex, like:
Regex.IsMatch( theString, "^[\w|\d]*$");

Please, the above regular expression was not tested , test it if you are
going to use it !!

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Nicholas Paldino said:
Darin,

You can cycle through all of the characters in the string, and then
check to see if the character is valid. You can do something like this:

// Assuming pchrChar is the character.
bool pblnAlphaNumeric = ('A' <= pchrChar && pchrChar <= 'Z') || ('a' <=
pchrChar && pchrChar <= 'z') || ('0' <= pchrChar && pchrChar <= '9');

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Darin Browne said:
Is there anything built into .NET Framework I could use
to check if a string only has numerics and alphanumerics
in it? If anything else but a numeric or alpha has been
entered I want it to error.

Thanks.
 
// Assuming pchrChar is the character.
bool pblnAlphaNumeric = ('A' <= pchrChar && pchrChar <= 'Z') || ('a' <=
pchrChar && pchrChar <= 'z') || ('0' <= pchrChar && pchrChar <= '9');

That's pretty i18n unfriendly code. I'd use Char.IsLetterOrDigit()
instead.



Mattias
 
Back
Top