validate that string input is a negative number

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I have a data entry windows form. One of the text boxes allows the user to
enter a string. I need this text box to only allow users to type in a
negative integer value (e.g. -1, -2, -3).

Current approach:
I want to validate the user's entry during the TextChanged() event. During
the validation, I need a function that will parse the string and see if it is
a negative integer. Does anyone have suggestions on the best way to do this?
or alternative approaches from what I have entered?
 
I have a data entry windows form. One of the text boxes allows the user
to
enter a string. I need this text box to only allow users to type in a
negative integer value (e.g. -1, -2, -3).

Current approach:
I want to validate the user's entry during the TextChanged() event.
During
the validation, I need a function that will parse the string and see if it
is
a negative integer. Does anyone have suggestions on the best way to do
this?
or alternative approaches from what I have entered?

Two different suggestions:

- Use int.TryParse to see if it is an integer, and then compare with zero
to see if it's negative.
- Use a regular expression such as "-\d+".

I have not run a benchmark, but I expect the TryParse approach to perform
faster.
 
Alberto said:
Two different suggestions:

- Use int.TryParse to see if it is an integer, and then compare with
zero to see if it's negative.
- Use a regular expression such as "-\d+".

I have not run a benchmark, but I expect the TryParse approach to
perform faster.

Also, that regular expression would pass "-0", which isn't negative.
 
Alberto Poblacion said:
Larry Lard said:
Also, that regular expression would pass "-0", which isn't negative.

Okay, let's refine it a little:

@"^-[1-9]\d*$"

lol sorry, have too:

-01 wouldn't pass the above expression pattern...

@"^-\d*[1-9]\d*$" should...haven't tested though...

Mythran
 
Or just a nice simple
int val;
return Int32.TryParse(s, out val) && val < 0

Exactly. This thread is a good example of why it's wise to avoid using
regular expressions where they're not truly advantageous :)
 

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

Back
Top