Can I validate that input is numeric without regular expressions?

L

-Lost

Can I validate that input is numeric without regular expressions?

I've just begun learning C# as of a week ago, so bear with me if I
utilize incorrect terminology (but feel free to correct me, please).

Anyway, I am trying to find a "standard" way of validating input to
the program. I need ONLY numeric arguments. I can do this with
regular expressions, but was wondering if there were any other
(possibly more correct) ways of doing it.

I was currently doing this:
scores.GetType().ToString() == typeof(String).FullName

So, it works to the extent that it will not allow me to declare an
instance of my custom class and pass string arguments to the
constructor.

However, I cannot pass command-line arguments because all console
input is read as string literals.

Or the Regex method:
Regex numericOnlyRegExp = new Regex("[a-z|A-Z]");
numericOnlyRegExp.IsMath("abc"); // if true return false

But I'd like to avoid this if possible (for no particular reason).

So... ? Thanks for any and all help!
 
P

Peter Duniho

Can I validate that input is numeric without regular expressions?

Yes, of course.
I've just begun learning C# as of a week ago, so bear with me if I
utilize incorrect terminology (but feel free to correct me, please).

Anyway, I am trying to find a "standard" way of validating input to
the program. I need ONLY numeric arguments. I can do this with
regular expressions, but was wondering if there were any other
(possibly more correct) ways of doing it.

IMHO, the easiest and most straight-forward way to validate text input as
being a valid numeric input is to attempt to convert it to a numeric
value. Use, for example, Int32.TryParse() to see if the string can be
converted to an int. All of the built-in numeric types (and many others,
for that matter) have a Parse() and TryParse() method that can be used for
this.
I was currently doing this:
scores.GetType().ToString() == typeof(String).FullName

So, it works to the extent that it will not allow me to declare an
instance of my custom class and pass string arguments to the
constructor.


I don't understand how this relates to your question. The code you posted
validates the argument as being a string (sort of...to do that, you should
actually use "scores is string" rather than comparing the type names),
not as being numeric.
However, I cannot pass command-line arguments because all console
input is read as string literals.

A "literal" is something you've hard-coded. A "variable" is something
that can change at run-time. So, console input is read as (stored in)
string variables, not string literals.
Or the Regex method:
Regex numericOnlyRegExp = new Regex("[a-z|A-Z]");
numericOnlyRegExp.IsMath("abc"); // if true return false

How does that ensure that the input is numeric? It will tell you if there
are characters from the English alphabet, but that's about it. There are
all sorts of other characters that could be in there that would prevent
the data from being numeric.
But I'd like to avoid this if possible (for no particular reason).

Well, you should avoid this if possible, for a very good reason: it
doesn't ensure that your input is numeric. :)

Pete
 
C

christery

so... there is Google...

if (string.IsNullOrEmpty(myArgument))
throw new ArgumentNullException("...");

if (!Int32.IsNumeric(myArgument))
throw new ArgumentException("...");

and there is MSDN... and books and coworkers and...

//CY Who stole chr$(12)?
 
P

Peter Duniho

so... there is Google...
Yes?

if (string.IsNullOrEmpty(myArgument))
throw new ArgumentNullException("...");

This doesn't tell you if input is numeric.
if (!Int32.IsNumeric(myArgument))
throw new ArgumentException("...");

There's no such thing as Int32.IsNumeric().

I'm not really sure what the point of your reply was. Care to clarify?

Pete
 
C

christery

There is in C and just following thehttp://davidhayden.com/blog/dave/archive/2005/01/16/779.aspx
I thought it was the same in c#

pseudo:if its not nothing or its not a number then ...

But just parse and hope.. 4 all I care.

Hope that claryfied it... I should just test code before offering as
an answer

Happy regex

//CY

just add the reference to microsoft.visualbasic and it should work...
not tested but... what the heck..
its called information.isnumeric or something..
//CY
 
N

Nicholas Paldino [.NET/C# MVP]

It should be noted that link is wrong. While there is a section in the
MSDN documentation "IsNumeric [C#]" (which confuses me, to be honest), it
references an article about determining if a string value is numeric, not a
method on Int32.

There ^is^ an IsNumeric method in .NET though, it is a static method on
the Information class in the Microsoft.VisualBasic namespace (which you can
access by referencing Microsoft.VisualBasic).

However, this will give you different behavior than the TryParse methods
on the numeric types in .NET.


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

There's no such thing as Int32.IsNumeric().

I'm not really sure what the point of your reply was. Care to clarify?

Pete

There is in C and just following the
http://davidhayden.com/blog/dave/archive/2005/01/16/779.aspx
I thought it was the same in c#

pseudo:if its not nothing or its not a number then ...

But just parse and hope.. 4 all I care.

Hope that claryfied it... I should just test code before offering as
an answer

Happy regex

//CY
 
C

christery

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualBasic;

namespace Test
{
class Slask
{
static void Main()
{

bool x = Information.IsNumeric("987");
Console.WriteLine("{0}", x);
x = Information.IsNumeric("987x");
Console.WriteLine("{0}", x);
Console.ReadKey();
}
}
}

True
False

Works for me...

//CY
 
N

Nicholas Paldino [.NET/C# MVP]

Yes, but IsNumeric is not a C# intrinsic method or a method on the Int32
structure (which is what is implied by the article that was linked to).

While it has a Microsoft.VisualBasic namespace, it's really just another
method in another type in another assembly accessible in .NET.
 
M

Mihai N.

Can I validate that input is numeric without regular expressions?

TryParse() is probably the right thing.
But 12,345,678.98 is also numeric, so if this is what you want Int32
is not the right type (obviously).
TryParse will also be aware of various languages (where the decimal
separator is not dot, and thousand separator is not comma).
 
C

Cor Ligthert[MVP]

-Lost

First you have to state what you call numeric input.

Exponent and other signs can be in that.

If you mean only characters in the range from 0 to 9 then it is easy to
evaluate by its byte range.

Cor
 
C

Cor Ligthert[MVP]

Nicholas.

The IsNumeric in VB is just a try catch from a parse (probably now a
tryparse, never investigated it after 2003)

I don't think that it is has advantage for that to include the Microsoft
Visual Basic namespace, because it easy to make as your own class. (However,
like the parse is it evalutating the extra numeric characters as by instance
Exponent as valid).

Cor
 
N

Nicholas Paldino [.NET/C# MVP]

Cor,

No, there is more to it than that. Ultimately, it can boil down to a
TryParse, but the behavior of IsNumeric in umanaged VB (and the current VB)
is different than calling TryParse on double. IsNumeric will also convert
hex and octal sequences, as well as not call TryParse at all if the type is
a numeric type to begin with (TryParse accepts only strings whereas
IsNumeric will accept ANY type).
 
C

christery

(However, like the parse is it evalutating the extra numeric characters as
Yup, but didnt think hex would wor, and it didnt, if I didnt code
wrong

x = Information.IsNumeric("987E+2"); //True
Console.WriteLine("{0}", x);
x = Information.IsNumeric("0x2B"); //False
Console.WriteLine("{0}", x);

Maybe should be called is decimal ;)

happy regex on 987e+2

//CY
 
C

Cor Ligthert[MVP]

Nicholas,

However, the Visual Basic IsNumeric is AFAI can see in fact build around a
try catch, and not a new implementation around caching errors with dates.

If you want to try it, set your debug options to catch any error and you
will see it.
(Or easier have a look at the fist time it attempts, then it has all
behaviour of a try catch)

Cor
 
C

Cor Ligthert[MVP]

Nicholas,

Duh, why would I check if I convert a numeric to an integer to a double if
an integer is numeric?

If it is about double to integer, then it has to be widened, but that is
something completely different.

Cor
 
L

-Lost

Response to "Cor Ligthert said:
First you have to state what you call numeric input.

Exponent and other signs can be in that.

If you mean only characters in the range from 0 to 9 then it is
easy to evaluate by its byte range.

Good point, Cor. I meant that I wanted anything that could be
considered a number, but otherwise exclude [a-z|A-Z].

Thanks.
 
L

-Lost

Response to "Peter Duniho said:
IMHO, the easiest and most straight-forward way to validate text
input as being a valid numeric input is to attempt to convert it
to a numeric value. Use, for example, Int32.TryParse() to see if
the string can be converted to an int. All of the built-in
numeric types (and many others, for that matter) have a Parse()
and TryParse() method that can be used for this.

Thanks. I hadn't quite got to TryParse yet.
I was currently doing this:
scores.GetType().ToString() == typeof(String).FullName

So, it works to the extent that it will not allow me to declare
an instance of my custom class and pass string arguments to the
constructor.


I don't understand how this relates to your question. The code
you posted validates the argument as being a string (sort of...to
do that, you should actually use "scores is string" rather
than comparing the type names), not as being numeric.


If for example I was doing this:

myAverageClass average = new myAverageClass(100, "90", 80);

I wanted to be able to catch that. However, it disallowed me being
able to pass arguments via the command-line (as they were all caught
by it).
A "literal" is something you've hard-coded. A "variable" is
something that can change at run-time. So, console input is read
as (stored in) string variables, not string literals.

I knew that for the most part, but didn't know it extended to
something passed via the command-line. Thanks.
Or the Regex method:
Regex numericOnlyRegExp = new Regex("[a-z|A-Z]");
numericOnlyRegExp.IsMath("abc"); // if true return false

How does that ensure that the input is numeric? It will tell you
if there are characters from the English alphabet, but that's
about it. There are all sorts of other characters that could be
in there that would prevent the data from being numeric.
But I'd like to avoid this if possible (for no particular
reason).

Well, you should avoid this if possible, for a very good reason:
it doesn't ensure that your input is numeric. :)

All good points -- especially after I considered format specifiers.

Thanks, Pete, for your detailed response.
 
L

-Lost

Response to "Mihai N. said:
TryParse() is probably the right thing.
But 12,345,678.98 is also numeric, so if this is what you want Int32
is not the right type (obviously).
TryParse will also be aware of various languages (where the decimal
separator is not dot, and thousand separator is not comma).

Gotcha. Int32.TryParse || Double.TryParse. Thanks.
 
P

Peter Duniho

[...]
I was currently doing this:
scores.GetType().ToString() == typeof(String).FullName

So, it works to the extent that it will not allow me to declare
an instance of my custom class and pass string arguments to the
constructor.


I don't understand how this relates to your question. The code
you posted validates the argument as being a string (sort of...to
do that, you should actually use "scores is string" rather
than comparing the type names), not as being numeric.


If for example I was doing this:

myAverageClass average = new myAverageClass(100, "90", 80);

I wanted to be able to catch that. However, it disallowed me being
able to pass arguments via the command-line (as they were all caught
by it).


I still don't understand. You want to be able to catch what? What
disallowed you being able to pass arguments via the command-line? And
what does constructing a new instance of "myAverageClass" have to do with
the command-line arguments?

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top