Reputation: 1477
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??
Upvotes: 2
Views: 1505
Reputation: 14079
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]
Upvotes: 0