Reputation: 185
Instead of using if (numberEntered < 1 || numberEntered > 24), is it possible to use a regex to check whether the field is in a 24 hour clock format e.g. 23:00.
private void textBox4_Validating(object sender, CancelEventArgs e)
{
{
int numberEntered;
if (int.TryParse(textBox4.Text, out numberEntered))
{
if (numberEntered < 1 || numberEntered > 28)
{
MessageBox.Show("You have to enter a number between 1 and 28");
textBox4.Text = 5.ToString();
}
}
else
{
MessageBox.Show("You need to enter an integer (number)");
textBox4.Text = 5.ToString();
}
}
Upvotes: 1
Views: 649
Reputation: 33153
As Jonas says, using DateTime.TryParse
is preferable to using a regex, however, you might want to consider using a DataTimePicker
control.
If you set the Format
property to Custom
and then set the CustomFormat
property to HH:mm
you will get a textbox like control that restricts input to 24hr time.
Finally, if you set ShowUpDown
to true
you will no longer have the calendar visible but have an updown instead.
Upvotes: 0
Reputation: 31428
string time = "23:00";
var time24 = new Regex(@"^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$");
bool is24hTime = time24.IsMatch(time);
Would probably work but I think that DateTime.TryParse is the way to go.
Upvotes: 2
Reputation: 14279
Is it possible? Yes. Is it preferred? No. It is better to parse the string into an integer and validate as you are currently doing then to use a regular expression. Regular expressions weren't really made to do what you are asking them to so the resulting regex would be awkward.
Upvotes: 1
Reputation: 5914
Use http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Upvotes: 0