WPF TextBox Validating Currency


In this post we’ll do a simple program that has a TextBox that asks the user to enter in a dollar amount and click the button to “submit” the dollar amount. This amount is in dollars and cents, such as in the USA or Canada or other parts of the world. Our program will not allow the user to enter alpha characters from the keyboard. If they type a letter, for example, nothing will happen at the interface. The user will follow a specific format to be validated.

Below is the XAML code.

<Window x:Class="ValidatingUSCurrency.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:ValidatingUSCurrency"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="ValidatingUSCurrency" Height="320" Width="510">
    <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
        US or Canadian currency to be typed in. We will allow numeric characters 0-9, the dollar sign, the negative sign
            commas, and the period. There is a maximum of 18 characters allowed.
        To do that we'll use a regular expression against every single keystoke at the keyboard.
        We'll allow these characters to be typed in many times, but the user will need to click the
        Validate button to "submit" the value. The value will be validated against another regular expression.
        A simple MessageBox.Show() function will display the result as Good or No good.</TextBlock>
        <TextBlock Margin="6,6,6,6" TextWrapping="Wrap">Enter in a currency that includes an optional negative sign,
        a dollar sign, digits, a decimal point and exactly two digits
        following the decimal point, such as: <Run>$45.07</Run> or <Run>$7,823.56</Run> or <Run>-$82.00</Run>. It must be in this format to pass 
        validation, including any comma separators.</TextBlock>
        <TextBox Name="txtbxUSCurrency" Margin="6,6,6,6" Width="180" Height="26" 
                 PreviewTextInput="TxtbxUSCurrency_PreviewTextInput"  MaxLength="18"></TextBox>
        <Button Name="btnValidateUSCurrency" Width="120" Height="25" Click="BtnValidateUSCurrency_Click">Validate</Button>
    </StackPanel>
</Window>

Below is the C# code. The PreviewTextInput controls which characters will be accepted when the user types them at the keyboard. It acts like a filter. Understand that this is keystroke by keystroke. To validate the entire number, the user clicks the Validate button and we use another regular expression to check if the number is in the correct and acceptable format.

using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
namespace ValidatingUSCurrency
{
    public partial class MainWindow : Window
    {
        private static Regex Rgx = new Regex(@"^\-?\$\d{1,3}(,\d{3})*\.\d\d$");

        public MainWindow()
        {
            InitializeComponent();
        }
        private void TxtbxUSCurrency_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !IsTextAllowed(e.Text);
        }
        private static readonly Regex rgx = new Regex(@"[0-9.$,-]");
        private static bool IsTextAllowed(string text)
        {
            return rgx.IsMatch(text);
        }
        private void BtnValidateUSCurrency_Click(object sender, RoutedEventArgs e)
        {
            if (Rgx.IsMatch(txtbxUSCurrency.Text))
            {
                MessageBox.Show("Good");
            }
            else
            {
                MessageBox.Show("No good.");
            }
        }
    }
}