2

My goal is to write/extend a WPF textbox that can limit user by entering some invalid characters. So allowed characters is going to be a Regex.

Here is what I did :

 public class MyTextBox : TextBox
{
    static MyTextBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyTextBox),
         new FrameworkPropertyMetadata(typeof(MyTextBox)));
        TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(TextPropertyChanged)));

    }

    public MyTextBox()
    {
       PreviewTextInput +=MyTextBox_PreviewTextInput;
    }
    void MyTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
    {
        var tb = sender as MyTextBox;
        if (tb == null) return;

        if (IsMasking(tb) && !Regex.IsMatch(e.Text, Mask))
        {
            e.Handled = true;
        }
    }

   private static bool IsMasking(MyTextBox tb)
    {
        if (string.IsNullOrWhiteSpace(tb.Mask)) return false;
        try
        {
            new Regex(tb.Mask);
        }
        catch (Exception)
        {
                           return false;
        }
        return true;
    }

    #region Mask Dependancy property
    public string Mask
    {
        get { return (string)GetValue(MaskProperty); }
        set { SetValue(MaskProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Mask.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MaskProperty =
        DependencyProperty.Register("Mask", typeof(string), typeof(MyTextBox), new PropertyMetadata(string.Empty));

    #endregion


}

Usage:

 <ctrlLib:MyTextBox  Watermark="Test WM" Width="350" Margin="20" 
                        Mask="^[A-Z][0-9]{2}$"
                        PreviewTextInput="UIElement_OnPreviewTextInput"/>

So I want to allow only alpha followed by two integers. My control doesnot even take any character as input

What is wrong I am doing or how to fix it? I guess since regex is for the entire string typing in single character does not do the trick??

WPFKK
  • 1,419
  • 3
  • 20
  • 42

1 Answers1

0

This should do the trick

^[A-Za-z]*\d\d$

You were close you just needed to put a start after [A-Z]

I made it case insensitive and used \d as a shorthand for [0-9]

buckley
  • 13,690
  • 3
  • 53
  • 61
  • Nope: did not work. I guess something to do with Regext itself since its not a complete string... does it ring a bell? – WPFKK Dec 29 '15 at 15:37
  • Hmm.. Can you try ^aa$ as the pattern? Now it should only accept aa (nothing before and nothing after allowed). – buckley Dec 29 '15 at 17:01