Windows Develop Bookmark and Share   
 index > Windows Forms Data Controls and Databinding > Setting masked textbox to validate time in 12hr format
 

Setting masked textbox to validate time in 12hr format

Hi All,

I have one urgent requirement. I need to set masked textbox in below format 12:59 AM
User can key in hour :min: AM/PM.

It need to be validated by 12 hr format

pls help
Ranjani  Monday, August 03, 2009 1:38 PM

Hi Ranjani,

I have found another simple solution. We can use DateTimePicker to achieve your goal. We need to set some properties to meet your needs. These are the values of some properties:
ShowUpDown : true

Format : Custom

CustomFormat : hh:mm tt

Let me know if this helps.
Aland Li


Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
Aland Li  Monday, August 10, 2009 9:24 AM
Hey thanks for ur reply .... I was initially using datetimepicker instead of that only i was asked to use masked textbox.
In the mask property i have given custom and the below format
00:00 LL and have done validation using Regular expression . The expression i used is
Regex timeRegex = new Regex(@"^([0]?[1-9]|[1][0-2]):([0-5][0-9]|[1-9]) [AP]M$");


Thanks & Regards,
Ranjani
  • Marked As Answer byRanjani Thursday, August 13, 2009 4:21 AM
  •  
Ranjani  Thursday, August 13, 2009 4:21 AM

Hi Ranjani,

As far as I know, MaskTextBox does not support such a case. The most difficult part is to check ‘AM/PM� I have another solution, we can create our own TextBox and override the OnKeyPress method to check and avoid the illegal typed character. You can also handle the KeyPress event of a TextBox to do the same thing. This is the code snippet:

public class TimeTextBox : TextBox
    {
        //Check typed character and avoid illegal character.
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            //Save the old states.
            string txt = this.Text;
            int selectStart = this.SelectionStart;
            int selectLen = this.SelectionLength;
            if (Char.IsControl(e.KeyChar) == false)
            {
                //Cope with the common char, such as A,B,C,!,1,2
                txt = txt.Remove(selectStart, selectLen);
                txt = txt.Insert(selectStart, e.KeyChar.ToString());
                selectStart += 1;
            }
            else
            {
                //Cope with control key.
                Keys cmdKey = (Keys)e.KeyChar;
                if (cmdKey == Keys.Delete)
                {
                    if (selectLen == 0 && selectStart < txt.Length)
                        txt = txt.Remove(selectStart + 1);
                    else
                        txt = txt.Remove(selectStart, selectLen);
                }
                else if (cmdKey == Keys.Back)
                {
                    if (selectLen == 0 && selectStart > 0)
                    {
                        txt = txt.Remove(selectStart - 1);
                        selectStart -= 1;
                    }
                    else
                        txt = txt.Remove(selectStart, selectLen);
                }
            }

            if (ValidText(txt))
            {
                //Reset the text and states.
                this.Text = txt.ToUpper();
                this.SelectionStart = selectStart;
            }            
            e.Handled = true;
        }

        //Check if the typed character would generate a legal text
        private bool ValidText(string txt)
        {
            bool isLegal = true;
            for (int i = 0; i < txt.Length; i++)
            {                
                char c = txt[i];
                bool isCharLegal = false;
                switch (i)
                {
                    case 0:
                        {
                            //The first character must be 0 or 1
                            if (c == '0' || c == '1')
                                isCharLegal = true;
                            break;
                        }
                    case 1:
                        {
                            //The second character depends on the first character
                            //If the first is 0, this character can range from 1 to 9,
                            //else it must be 1 or 2
                            if((txt[0] == '0' && (c >= '1' && c <= '9'))
                                || ((txt[0] == '1') && (c == '1' || c == '2')))
                                isCharLegal = true;
                            break;
                        }
                    case 2:
                        {
                            //The third character must be ':'
                            if (c == ':')
                                isCharLegal = true;
                            break;
                        }
                    case 3:
                        {
                            //The fourth character must range from 0 to 5,
                            //because minites must range from 0 to 59
                            if (c >= '0' && c <= '5')
                                isCharLegal = true;
                            break;
                        }
                    case 4:
                        {
                            //The fifth character can be any digit.
                            if (Char.IsDigit(c))
                                isCharLegal = true;
                            break;
                        }
                    case 5:
                        {
                            //The sixth character must be a blank to split the time and AM/PM
                            if (Char.IsWhiteSpace(c))
                                isCharLegal = true;
                            break;
                        }
                    case 6:
                        {
                            //The seventh character can be A or P, a lower character is also legal.
                            if (c == 'A' || c == 'P'
                                || c == 'a' || c == 'p')
                                isCharLegal = true;
                            break;
                        }
                    case 7:
                        {
                            //The eighth character can be M, a lower character is also legal.
                            if (c == 'M' || c == 'm')
                                isCharLegal = true;
                            break;
                        }
                    default:
                        break;

                }
                if (isCharLegal == false)
                {
                    //If one character is illegal, the string is illegal.
                    isLegal = false;
                    break;
                }
            }
            return isLegal;
        }
    }



Let me know if this helps.
Aland Li


Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
Aland Li  Wednesday, August 05, 2009 7:10 AM

Hi Ranjani,

I have found another simple solution. We can use DateTimePicker to achieve your goal. We need to set some properties to meet your needs. These are the values of some properties:
ShowUpDown : true

Format : Custom

CustomFormat : hh:mm tt

Let me know if this helps.
Aland Li


Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
Aland Li  Monday, August 10, 2009 9:24 AM
Hey thanks for ur reply .... I was initially using datetimepicker instead of that only i was asked to use masked textbox.
In the mask property i have given custom and the below format
00:00 LL and have done validation using Regular expression . The expression i used is
Regex timeRegex = new Regex(@"^([0]?[1-9]|[1][0-2]):([0-5][0-9]|[1-9]) [AP]M$");


Thanks & Regards,
Ranjani
  • Marked As Answer byRanjani Thursday, August 13, 2009 4:21 AM
  •  
Ranjani  Thursday, August 13, 2009 4:21 AM

You can use google to search for other answers

Custom Search

More Threads

• Positioning context menu over datagridview
• select a row from the rowheader..
• How to allow the user to create a combo box at runtime and save it.
• How to fire an event after an item is added or deleted...
• setting an Image column in a datagrid view based on a value in the database c#
• How to create "INotifyPropertyChanged" Change Notification in Visual C#.NET 2005 Express?
• master/Detail problem
• copy file from a server using internet
• Table information doesn't show...
• Datagridview KeyDown Event