Search code examples
c#winformstextboxcurrencyrestrict

Restrict Characters Allowed In TextBox(Entering Money Amount)


So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.


Solution

  • I think you are using WinForms and not WPF. If that is the case then you could use System.Windows.Forms.ErrorProvider (you can drag-drop one from toolbox to your form) along with regular expressions to do the validation.

    WARNING: The regex pattern string below may not do exactly you want but hopefully conveys the idea.

    Some match examples... "$4,000.00", "-$4000.00", "-$400.00"

        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            string error = null;
            string pattern = @"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$";
    
            if (!Regex.IsMatch(textBox1.Text, pattern))
            {
                error = "Please enter a US currency value.";
                e.Cancel = true;
            }
            errorProvider1.SetError((Control)sender, error);
        }