How to validate a TextBox field against a Natural Number? User are restricted to input natural number (e.g. 1,2,3..99999) and if not, a MessageBox is shown.
Currently I’m using the following code (assuming the natural number does not go beyond two digits):
Regex isPositiveNum2 = new Regex("[1-9]");
Regex isPositiveNum = new Regex("[1-9][1-9]");
if (isPositiveNum.IsMatch(textbox1.Text) == true ||
isPositiveNum2.IsMatch(textbox1.Text) == true)
{
/* Do something */
}
else
{
MessageBox.Show("Hey! This is not a Natural Number");
textbox1.Text = "1";
}
This works alright, but I’m sure it’s not the best approach. Hope something can suggest something better.
Use the built in parsing:
This will throw an exception if
textbox1.Textcan’t be parsed, so you may want to useTryParseinstead: