1

Whenever the user tries to enter a number not in the range [0, 24] it should show an error message. My code to accept floating point numbers is as follows. How can I modify it to add range validation?

private void h(object sender, Windows.UI.Xaml.Controls.TextChangedEventArgs e)
{        
   try
   {
      float time = float.Parse(hours.Text);
   }
   catch
   { 
      label2.Text = "enter proper value ";
      hours.Text = " ";
   } 
}
2
  • 2
    if(time > 0 && time < 24) ?? Commented May 5, 2013 at 10:50
  • you can use a simple regex and validate the input against the regex. Again this regex can be read from a config file so that you can plug any validation logic and change the behavior w/o application recompile at runtime Commented May 5, 2013 at 11:50

2 Answers 2

2

I know SO discourages just posting a link as an answer but in the case the link is a direct and full answer to the question.

Validation Class

Sign up to request clarification or add additional context in comments.

1 Comment

You can summarize the content contained in the link to provide a useful answer, and then provide the link for further reference.
0

I would recommend using float.TryParse, rather than building a try-catch block in case the parse fails. TryParse will return the value of the parse in the out variable, and true if the parse is successful and false if it isn't. Combine that with a check to see if the number is between 0 and 24, and you have something that looks like this:

float parsedValue;

// If the parse fails, or the parsed value is less than 0 or greater than 24,
// show an error message
if (!float.TryParse(hours.Text, out parsedValue) || parsedValue < 0 || parsedValue > 24)
{
    label2.Text = "Enter a value from 0 to 24";
    hours.Text = " ";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.