Time validation in TextBox. Validating a textbox for some regular expression

前端 未结 3 891
北荒
北荒 2021-01-28 11:38

I\'ve to make a textbox(WPF) for entering time with validation. I want to enter a regular expression validation for time (6:12 am).

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-28 12:15

    How about this one :

    class TimeTextBox : TextBox
    {
        public Boolean IsProperTime { get; set; }
    
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            DateTime time;
    
            if (String.IsNullOrEmpty(Text) || !DateTime.TryParse(Text, out time))
            {
                IsProperTime = false;
            }
            else
            {
                IsProperTime = true;
            }
    
            UpdateVisual();
    
            base.OnTextChanged(e);
        }
    
        private void UpdateVisual()
        {
            if (!IsProperTime)
            {
                BorderBrush = Brushes.Red;
                BorderThickness = new Thickness(1);
            }
            else
            {
                ClearValue(BorderBrushProperty);
                ClearValue(BorderThicknessProperty);
            }
        }
    }
    

    You can change the time parsing logic in there.

提交回复
热议问题