0

I want to validate (in some simple way) if the input text for a textbox is a number, I would use this code: LINK

But here's a problem: I use .NET 4.0 not 4.5, so I don't havePreviewTextInput event.

I could use TextChanged, but now it doesn't have e.Handled validator.

Is there any simple solution for this (I want to avoid tons of code)?

Community
  • 1
  • 1
Nickon
  • 9,652
  • 12
  • 64
  • 119
  • 1
    Can't you just use tryparse ? – reggaemahn Jul 29 '13 at 14:57
  • use a masked textbox, then you need no validation – Jonesopolis Jul 29 '13 at 14:58
  • can you use the `char.IsNumeric` function much easier in my opinion – MethodMan Jul 29 '13 at 14:58
  • Use `TryParse` and deal with the exception. Or, if you wish to be adventurous, try RegEx! For just validation that it is a number, RegEx is actually pretty simple. – Daniel Underwood Jul 29 '13 at 14:59
  • @DJKRAZE Wouldn't `char.IsNumeric` only work with single digit numbers? – Daniel Underwood Jul 29 '13 at 15:01
  • @danielu13: If it works for single numbers making it work for an entire string is trivial. – Guvante Jul 29 '13 at 15:03
  • it will work on a string if the `OP` wants to check the whole string char by char in a for loop or foreach loop – MethodMan Jul 29 '13 at 15:03
  • @danielu13 - A simple way to address your concern would be to convert the `String` into a `char` array and check each element of the array if its a number. You could strip certain characters away from the string to prevent it say failing when `999-999-9999` was entered. – Security Hound Jul 29 '13 at 15:04
  • I wanted to cancel the event if it's not numeric. Im not retarded:D I know how to check if the string is a number. But I wanted to know if I should remember the old value of the textbox, then validate the new, if not a number, write the old. `PreviewTextInput` supports event cancellation, but it's not available in 4.0 framework – Nickon Jul 30 '13 at 07:16

2 Answers2

2

If you have access to the property that will hold the value, you can use a DataAnnotation on the property.

[RegularExpression(Pattern="[0-9]+")]
public string MyProperty { get; set; }

This MSDN article goes abit more in depth about the subject.

ywm
  • 1,107
  • 10
  • 14
0

It is difficult to determine what a number is and isn't. I would use TryParse. If it fails it's not a number.

string s = "12345";

int number;
bool result = int.TryParse(s, out number);

if(!result)
{
    // not a number.
}
Sam Leach
  • 12,746
  • 9
  • 45
  • 73
  • Ye, but I said I don't have `e.Handled` validator. So I can't escape the event I thought there's some simple way to do this. Like `PreviewTextInput` in 4.5 – Nickon Jul 30 '13 at 07:12