-1

I want to validate the input on a textbox on a Windows Forms application i.e. show a message box with an error if the number entered is lower than 1 or greater than 24 or if any other character besides an integer is entered. How would I go about doing this?

2

5 Answers 5

3

I would consider something like:

 //make sure that we have a valid number in the text box with no other characters //loop through the string, examining each character for (int i = 0; i < txtHour.Text.Length; i++) { //if this character isn't a number, then don't close the form or continue if (!char.IsNumber(txtHour.Text[i])) { MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24"); return; } } //now that we know we have a valid number, convert the string to int and make sure it's not less than 1 or greater than 24 int testInt = Convert.ToInt32(txtHour.Text); if (testInt < 1 || testInt > 24) { MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24"); return; } 

For the method example that you asked for in your comment you could do something more like:

 ////////////////////////////////////////////////////////////////////// //in your main code: if (!isValidHour(textBox1.Text)) MessageBox.Show("Value for field must be a number from 1 to 24"); if (!isValidHour(textBox2.Text)) MessageBox.Show("Value for field must be a number from 1 to 24"); ////////////////////////////////////////////////////////////////////// ///method to validate if text field is an INT from 1 to 24 bool isValidHour (string stringToValidate) { //make sure that we have a valid number in the text box with no other characters //loop through the string, examining each character for (int i = 0; i < stringToValidate.Length; i++) { //if this character isn't a number, then don't close the form or continue if (!char.IsNumber(stringToValidate[i])) { //MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24"); return false; } } //now that we know we have a valid number, convert the string to int and make sure it's not less than 1 or greater than 24 int testInt = Convert.ToInt32(stringToValidate); if (testInt < 1 || testInt > 24) { //MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24"); return false; } return true; } 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this works perfectly. To expand this for say validating input for 2-3 text boxes would it be a case of using the same block of code but changing the textbox name and creating a new int or is there a way of validating the input of multiple text boxes in the exact same was as above but in one block of code?
@user2929108 - see new code block for one possible answer to this question
the line int testInt = Convert.ToInt32(stringToValidate); throws a FormatException error
@user2929108 - I can't reproduce your issue, and I don't have your code to comment on. The only issue I can find with the code block that I wrote above is that if the number in the textbox is more than 32 bits, there will be an overflow exception on Convert.ToInt32, but you could easily just add a try block or a char count to prevent that. If you don't show any of your own code, no one here will be able to tell you why you get a FormatException. Your question was already put on-hold and marked as off-topic (rightfully so) for this very reason.
1
try{ if((int)item.value >= 1 && (int)item.value <=25){ //match. }else{ //error. } }catch (Exception e){ //type error } //or--- var itemValue = default(int); if(int.TryParse(item.value, out itemValue)){ if(itemValue >= 1 && itemValue <= 25){ //match. }else{ //error. } }else{ //item.value is not numeric. } 

5 Comments

Should you use int.Parse here or even better int.TryParse ? What is the meaning of catch block here?
I put it in as an attempt to parse something that is not numeric. If the catch executes, it would mean that the input was not numeric. If you dont want to use the catch, the try parse would suffice doing the same thing. It would check to see if it is possible to parse it into a numeric.
TryParse has a second parameter, marked as out. You don't need to parse item.value several times. The error would also be shown, if the value is not a number.
Hi. Thanks for the response although I'm not sure how to fit the code to my program. The textbox I want to apply this to is called txtHour
I wouldn't even try the first example as it is quite possible that the item.value is a string and won't even cast.
1

You can add a private method and call it wherever necessary by passing textbox control which needs to be validated.

 private void ValidateText(TextBox textbox) { int value; bool isConverted = Int32.TryParse(textbox.Text.Trim(), out value); if (!isConverted) { MessageBox.Show("Only numbers allowed"); return; } if (value < 1 || value > 24) { MessageBox.Show("Please enter a value between 1-24"); } } 

Validating txtHour by invoking above method

ValidateText(txtHour); 

Comments

0

Look into doing your check with the OnKeyPress/OnKeyDown/OnKeyUp events:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

Comments

0

This is a very simplistic implementation but, this will achieve the validation that you are asking for:

int hoursEntered; bool isInteger; isInteger = int.TryParse(txtHour.Text, out hoursEntered); if (hoursEntered < 1 || hoursEntered > 24 && isInteger == true) MessageBox.Show("Your number is either less than 1, greater than 24 or you didn't enter a number", "Warning!", MessageBoxButtons.OK); 

There are a few things to consider here though. I wrote this code and had it tied to the event handler for a button click. If that is not your implementation, then I would strongly consider using the OnKeyPress/OnKeyUp/OneKeyDown events to do your validation. Otherwise, you can just copy this code into whichever button click event handler you already have in-place.

2 Comments

The input "2a" would parse as 2...which would still be a failure according to the op.
@ChrisLively - You are 100% correct. Unfortunately, I was called into a last minute meeting while posting the answer and didn't get to finish it up. Dizzy.stackoverflow has already posted the answer I was driving towards.