Implementing Numeric Input Validation in WPF TextBox

Nov 10, 2025 · Programming · 9 views · 7.8

Keywords: WPF | TextBox | Numeric Input Validation

Abstract: This article provides a comprehensive guide to implementing numeric input validation in WPF TextBox controls. It covers core techniques including PreviewTextInput event handling, regular expression validation, and paste operation interception, with complete code examples and best practice recommendations.

Introduction

In WPF application development, restricting user input in TextBox controls to specific character types is a common requirement. Particularly in scenarios requiring numeric input, preventing non-numeric characters is crucial for maintaining data integrity and avoiding runtime exceptions. While the traditional NumericUpDown control provides numeric input functionality, its built-in up/down arrow buttons may not be suitable for all application contexts, leading developers to prefer solutions that maintain the standard TextBox appearance and behavior.

Core Implementation Mechanism

WPF provides the PreviewTextInput event, which triggers before text is input into the control, allowing developers to validate and intercept input content. This serves as the fundamental technical approach for implementing numeric input restrictions.

Regular Expression-Based Validation

Using regular expressions for input validation is the most commonly employed and flexible method. By setting the e.Handled property in the PreviewTextInput event handler, invalid input can be effectively blocked.

private static readonly Regex _regex = new Regex("[^0-9.-]+");
private static bool IsTextAllowed(string text)
{
    return !_regex.IsMatch(text);
}

private void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !IsTextAllowed(e.Text);
}

The above code creates a regular expression that matches all characters except digits, decimal points, and minus signs. When disallowed characters are detected, e.Handled is set to true, preventing the characters from being entered into the TextBox.

Supplemental Paste Operation Prevention

Handling only the PreviewTextInput event does not prevent users from inputting illegal data through paste operations. For comprehensive protection, the DataObject.Pasting event must also be handled.

private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsTextAllowed(text))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}

Char.IsNumber Alternative Approach

For developers unfamiliar with regular expressions, the Char.IsNumber method can be used to achieve similar functionality. This approach offers advantages in terms of code readability.

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    e.Handled = !e.Text.All(cc => Char.IsNumber(cc));
}

Internationalization Considerations

When handling numeric input, differences in number formats across regions must be considered. Particularly, the decimal separator varies—some regions use commas instead of periods.

private void PositiveNumber(object sender, TextCompositionEventArgs e)
{
    char decSeparator = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
    e.Handled = !e.Text.All(cc => Char.IsNumber(cc) || cc == decSeparator);
}

XAML Configuration

In XAML, event handlers must be associated with the TextBox control:

<TextBox PreviewTextInput="PreviewTextInput" DataObject.Pasting="TextBoxPasting"/>

Performance Optimization Recommendations

For validation methods called frequently, it is recommended to declare regular expression objects as static members to avoid performance overhead from repeated creation. Additionally, for simple numeric validation, the Char.IsNumber method typically offers better performance than regular expressions.

Error Handling and User Experience

While blocking invalid input, appropriate user feedback should be provided. Using ToolTips, status messages, or visual cues to inform users of input restrictions can prevent confusion caused by unfamiliarity with the constraints.

Conclusion

By combining PreviewTextInput event handling with DataObject.Pasting event interception, effective numeric input restriction in WPF TextBox controls can be achieved. Developers can choose between regular expressions and the Char.IsNumber method based on specific requirements, with particular attention to number format compatibility in internationalization scenarios. This solution maintains the clean appearance of the TextBox while providing robust input validation capabilities.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.