Rohit
Rohit

Reputation: 6613

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

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).

Upvotes: 1

Views: 4420

Answers (3)

Hans Passant
Hans Passant

Reputation: 941397

Regex is not the right choice here. You ultimate do need to convert a string to a date or time. Use DateTime.TryParse() so you are always sure that if the validation allows it then the conversion will work as well.

Upvotes: 2

decyclone
decyclone

Reputation: 30830

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.

Upvotes: 2

Amsakanna
Amsakanna

Reputation: 12934

check this: http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errors.aspx for handling validation errors in controls

Else you can implement IDataErrorInfo in your viewmodel so that the Validation is embedded to your data itself.

Upvotes: 2

Related Questions