简体   繁体   中英

WPF Custom textbox to control user input using Regex

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??

This should do the trick

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

You were close you just needed to put a start after [AZ]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM