This WPF small project will demonstrate how to create a TextBox that only accepts alpha characters and spaces. We’ve created a TextBox, given it a Name and created a PreviewTextInput event for it.
Below is the XAMLcode.
<Window x:Class="ValidatingAlphaCharaters.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:ValidatingAlphaCharaters" mc:Ignorable="d" WindowStartupLocation="CenterScreen" Title="ValidatingAlphaCharaters" Height="300" Width="400"> <StackPanel Background="#A4C2F8C3"> <TextBlock Margin="6,6,6,6" TextWrapping="Wrap">Limit what the user can type into a TextBox! In this example we will only allow <Run FontWeight="Bold">alphabetical characters</Run> to be typed in. That is a to z in both upper and lower case, as well as spaces. We will not allow the Tab key or the Return key (to create a new line). We do not allow any numbers or other special characters on the keyboard such as the following: ! @ # $ % ^ & * ( ) _ + or any others.</TextBlock> <TextBox Name="txtbxAlpha" Margin="6,6,6,6" Width="280" Height="52" TextWrapping="Wrap" PreviewTextInput="TxtbxAlpha_PreviewTextInput" MaxLength="500"></TextBox> <TextBlock Margin="6,6,6,6" TextWrapping="Wrap">However, the use can still paste non-alpha characters into the above text box. Below is the Regex in the code behind. </TextBlock> <TextBlock Margin="6,6,6,6"><Run FontSize="14" FontWeight="Bold">Regex(@"^[\p{Lu}\p{Ll}]+$")</Run></TextBlock> </StackPanel> </Window>
Below is the C# code behind.
using System.Text.RegularExpressions; using System.Windows; using System.Windows.Input; namespace ValidatingAlphaCharaters { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void TxtbxAlpha_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !IsTextAllowed(e.Text); } private static readonly Regex rgx = new Regex(@"^[\p{Lu}\p{Ll}]+$"); private static bool IsTextAllowed(string text) { return rgx.IsMatch(text); } } }
Below is a brief explanation of the regular expression (Regex) code.
- ^ the beginning of the line, followed by . . .
- [ a character class that contains . . .
- \p{Lu} a lowercase Unicode letter, or . . .
- \p{Ll} an uppercase Unicode letter . . .
- ] the end of the character class . . .
- + that’s found one or more times, followed by . . .
- $ the end of the line.
In this project we do not allow the user to enter periods.