user1957558
user1957558

Reputation: 53

How to check text in textbox?

I'm trying to make a VideoClub application. I have a textbox named txtMovieDuration, where I want to type in the movie duration ofc.
What I did is, I allowed the user to write ONLY numbers in this format (hh:mm:ss). The dots appear automatically. BUT, there is this problem, that logicaly ss (seconds) and mm (minutes) can't be bigger than 59 (cuz they only go from 0 to 59). How can I check seconds and minutes to be < 60 ?

private void txtMovieDuration_TextChanged(object sender, EventArgs e)  
        {  
            txtMovieDuration.MaxLength = 8;

            if (txtMovieDuration.Text.Length == 2)
            {
                txtMovieDuration.Text += ":";
            }

            if (txtMovieDuration.Text.Length == 5)
            {
                txtMovieDuration.Text += ":";
            }

            txtMovieDuration.SelectionStart = txtMovieDuration.Text.Length;
         }

Upvotes: 0

Views: 1048

Answers (6)

Alvin Wong
Alvin Wong

Reputation: 12410

You can use a MaskedTextBox with the mask as 00:00:00 instead of using a normal TextBox which it will automatically add :s and only allow inputting numbers.

To check if the value of it is a valid time span value, set its ValidatingType to TimeSpan.

this.maskedTextBox1.ValidatingType = typeof(TimeSpan);

Then you can listen to the MaskedTextBox.TypeValidationCompleted event and use e.IsValidInput to determine if the user has entered a correct time span value.

Upvotes: 0

SWeko
SWeko

Reputation: 30882

Short answer: Use the DateTimePicker control, with it's format property set to Time.

However, if you are stuck using a textBox, you could

  • use a regex to check the format (as in @David Aleu's answer)
  • split the string on the separator (:) and validate the parts manually, like:

    string[] parts = txtMovieDuration.Text.Split(':');
    if (parts.Length !=3) //there must be a hh:mi:ss parts
    {
       MessageBox.Show("invalid time string");
       return;
    }
    int hours;
    if (int.TryParse(parts[0], out hours))
    {
       MessageBox.Show("the hours part is not a number");
       return;
    }
    //if you want to check the value of hours as sensible you could do it here
    //as there are very few movies longer than 10 hours
    int minutes;
    if (int.TryParse(parts[1], out minutes))
    {
       MessageBox.Show("the minutes part is not a number");
       return;
    }
    if ((minutes < 0) || (minutes > 59)
    {
       MessageBox.Show("the minutes part is out of range");
       return;
    }
    
    int seconds;
    if (int.TryParse(parts[2], out seconds))
    {
       MessageBox.Show("the seconds part is not a number");
       return;
    }
    if ((seconds < 0) || (seconds > 59)
    {
       MessageBox.Show("the seconds part is out of range");
       return;
    }
    //you can now make a TimeSpan object for the duration
    TimeSpan duration = new TimeSpan(hours, minutes, seconds);
    

    You could also not check the range of the hours/minutes/seconds variable, but (ab)use a feature of the TimeSpan constructor. Since the values are just converted to ticks, and the ticks used to initialize the TimeSpan, it's legal to do new TimeSpan(1000,2000,3000). It will create a timespan of 1000 hours, 2000 minutes (a.k.a. 33 hours 20 minutes) and 3000 seconds (aka 50 minutes), resulting in a timespan of 43 days, 2 hours and 10 minutes. This all means that you could do:

    TimeSpan duration = new TimeSpan(hours, minutes, seconds);
    if ((duration .Hours != hours)
         || (duration .Minutes != minutes) 
         || (duration .Seconds != seconds))
    {
       MessageBox.Show("the seconds part is out of range");
       return;
    }
    

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use TimeSpan.TryParse to validate the user input:

TimeSpan duration;
if (!TimeSpan.TryParse(txtMovieDuration.Text, out duration))
{
    MessageBox.Show("Please use correct format 'hh:mm:ss'!)");
}

You should consider to use an optional DateTimePicker control as SWeko has mentioned.

Upvotes: 4

William
William

Reputation: 221

Create a substring of the seconds.

String sub = txtMovieDuration.Text.Substring(6);
if(Convert.ToInt32(sub) < 60)
//Do something here

Do the same for minutes or do them together. Eg:

if(Convert.ToInt32(txtMovieDuration.Text.Substring(3,2)) && Convert.ToInt32(txtMovieDuration.Text.Substring(6)) > 60)
{ 
   //Error handling code

}

Note: I am assuming that the : are part of the string. If not, just change the substring start and end values.

Upvotes: 0

Eyad Alama
Eyad Alama

Reputation: 199

You can read the string value from the text box and convert it to Int or whatever data type you are using. More help on converting can be found here

Upvotes: 0

David Aleu
David Aleu

Reputation: 3942

What about if you do this?

public bool ValidateTime(string time)
{
     Regex regExp = new Regex(@"(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");

     return regExp.IsMatch(time);
}

Found here

Upvotes: 2

Related Questions