You prevent invalid characters in a WPF TextBox by deciding what counts as invalid, then enforcing that rule at the earliest layer that still gives users clear feedback: block keystrokes in PreviewTextInput and paste in DataObject.Pasting, validate the resulting string on TextChanged or through binding validation, and keep a final guard at the model or submit boundary. The key condition is that input filtering must match the data type and culture the value will actually be saved as—otherwise you block the wrong characters or let through values that fail later.
This article walks through those layers in the order you should implement them, shows working C# and XAML patterns for numeric, decimal, and pattern-constrained TextBoxes, and explains where each approach breaks. The examples target WPF on .NET (the same APIs exist on .NET Framework 4.x), and nothing here depends on a specific Visual Studio version.
Why TextBox input filtering is harder than it looks
A WPF TextBox is a general-purpose text editor, so it accepts whatever the user types, pastes, drags in, or receives through an IME. "Invalid character" is not a property of the TextBox—it's a property of your domain. A hyphen is invalid in a quantity field but required in a part number; a comma is a thousands separator in en-US and a decimal separator in de-DE. So before writing any handler, answer three questions:
1: What is the target type or format? Whole number, decimal, currency, phone number, identifier with a fixed pattern, or free text with a forbidden set? 2: What culture governs separators and digits? CultureInfo.CurrentCulture by default, or a fixed invariant format for machine-readable codes? 3: What should happen to input that arrives as a whole string rather than a keystroke—paste, drag-and-drop, autofill, or programmatic assignment?
Keystroke blocking alone answers none of questions 2 and 3 fully, which is why single-handler solutions tend to leak. The layered approach below is the standard, maintainable answer: filter early for feedback, validate at the string level for correctness, and validate again at the boundary for safety.
Prerequisites and the order of operations
Have a WPF project open with a window or user control containing at least one TextBox. You need basic familiarity with routed events, and if you plan to use binding validation, a view model with INotifyDataErrorInfo or IDataErrorInfo. Decide your rule first: for the worked examples I'll use a non-negative integer field, a decimal field that respects the current culture, and a code field limited to letters, digits, and hyphens.
Implement in this order, because each step catches what the previous one cannot:
1: Define the rule as a reusable predicate or parser, not inline logic in an event handler. 2: Block disallowed keystrokes in PreviewTextInput. 3: Intercept paste and drag-drop in DataObject.Pasting (and handle drop explicitly if you enable it). 4: Re-validate the full string after any change, including undo and programmatic sets. 5: Mirror the rule in binding validation so invalid text can never silently reach the model. 6: Enforce the same rule at the save/submit boundary.
Steps 2 and 3 are ergonomics; steps 4 through 6 are correctness. Skipping the later steps is the most common reason a "working" filter still lets bad data through.
Blocking keystrokes with PreviewTextInput
PreviewTextInput fires before the character is inserted, which makes it the right place to reject a single typed character. The event's Text property holds the character or composition result. A minimal numeric guard looks like this:
Two details matter. First, check the prospective string, not just the incoming character, when you have length or value limits—rejecting a keystroke based on the character alone misses constraints like "no more than nine digits." Second, char.IsDigit returns true for non-ASCII decimal digits such as Arabic-Indic numerals. That's often desirable for international users, but if your parser only accepts ASCII, use an explicit check like c >= '0' && c <= '9' instead, or normalize before parsing.
For the decimal field, a per-character test is not enough because validity depends on position: .5, 5., and 5.5.5 all contain only digits and one separator, but only the first two are parseable. Handle the cheap rejection in PreviewTextInput and defer the positional check to the full-string step:
Note the culture lookup. Hard-coding "." is the classic bug: a German user typing 1,5 gets the comma rejected, while a user in a comma-decimal locale who pastes 1.5 may end up with a value interpreted differently than intended. Reading NumberDecimalSeparator from the culture you will parse with keeps typing and parsing consistent. The same principle applies to group separators and the negative sign, which is not always - (some cultures and typographic conventions use a true minus sign U+2212).
PreviewTextInput does not fire for every kind of edit. Space and some control characters can arrive through PreviewKeyDown instead, and IME composition delivers text in a way that per-character filtering handles poorly. If you must block the spacebar specifically, add a PreviewKeyDown handler for Key.Space, but treat IME-heavy languages as a signal to rely more on full-string validation than on keystroke rejection.
Handling paste, drag-and-drop, and other bulk input
Paste bypasses PreviewTextInput entirely. The standard interception point is the attached DataObject.Pasting event, which fires before the pasted text is applied:
You have two design choices here, and they lead to different user experiences. Rejecting the entire paste (CancelCommand) is simple and predictable. Sanitizing instead—stripping invalid characters and inserting the rest—is friendlier for pasting from spreadsheets, where cells often carry trailing spaces or currency symbols, but it silently changes the user's data and can surprise them. Pick one and apply it consistently; mixing the two across fields makes the app feel arbitrary. If you sanitize, insert the cleaned text through the TextBox's editing commands rather than assigning Text directly, so undo history stays coherent.
Drag-and-drop into a TextBox is possible when AllowDrop is true and the control handles Drop. WPF's TextBox does not accept dropped text by default in all configurations, so if you enable it, validate the dropped payload with the same predicate before applying it. Autofill and programmatic assignment (box.Text = value) fire no input events at all—another reason the next layer exists.
Validating the full string after every change
The correctness layer evaluates the complete candidate string and decides whether it is acceptable. For a decimal field, the cleanest rule is "empty, or parses under the target culture"—with optional range limits:
Wire it to TextChanged, but be careful about what you do on failure. Reverting the text inside TextChanged (for example, restoring the last valid value) fights the user, breaks undo, and moves the caret unpredictably. A better pattern is to leave the text as typed, mark the field visually (border brush, tooltip), and let validation state—not silent correction—communicate the problem. Save the hard block for the submit boundary.
An important subtlety: decimal.TryParse with NumberStyles.Number accepts group separators, a leading sign, and surrounding white space, and it accepts some inputs you may not want, like 1,234 in a culture where the comma is a group separator. It also rejects a trailing separator such as 5. mid-typing in many cultures, which is why treating "empty or parseable" as valid and letting non-parseable intermediate states show as a warning—rather than blocking—produces a much less frustrating editing experience. Users type through invalid intermediate states constantly (-, 0., 1,).
If the field is bound with UpdateSourceTrigger=PropertyChanged, an unparseable string will trigger a conversion error before your TextChanged logic even matters. Either set UpdateSourceTrigger=LostFocus for typed numeric fields, or use a string-typed property in the view model that parses in its setter and exposes an error through INotifyDataErrorInfo. The string-property approach gives you full control and is the more testable design.
Restricting to a pattern: letters, digits, and separators
For identifier-like fields, a regular expression describes the rule compactly, and .NET's Regex supports timeouts that protect against pathological patterns:
Anchoring with ^ and $ and allowing zero length ({0,20}) makes the same pattern usable during editing and for final validation, so you don't maintain two subtly different rules. Test the prospective string rather than the single character, because patterns often constrain length and position, not just the alphabet. Keep the timeout: a user-supplied or later-edited pattern can backtrack catastrophically, and the timeout turns a freeze into an exception you can handle.
Unicode categories are often a better fit than [A-Za-z] when the field should accept international text. \p{L} matches letters in any script and \p{Nd} matches decimal digits; using them avoids telling a user with a non-Latin name that their letters are invalid. Decide deliberately whether "letters" means ASCII or Unicode, and say so in the field's help text if the distinction matters.
When input arrives through data binding and view models
If the TextBox is bound, invalid characters can also originate from code: a service returns a malformed string, a conversion produces unexpected output, or a computed property writes into the bound field. Binding-level validation catches these cases without touching the control:
Implement IDataErrorInfo or INotifyDataErrorInfo on the view model, expose the same predicate used in the UI, and let WPF render the error template. Use a ValidationRule on the Binding for simple, self-contained checks such as a regex or range. A ValidationRule runs during binding updates and can be reused across fields. Avoid IValueConverter for validation. A converter that returns DependencyProperty.UnsetValue produces a binding error with poor messaging; converters are for formatting, not for enforcing rules.
The payoff of sharing one predicate between the control handlers and the view model is that the rule cannot drift. If the UI blocks a character but the model accepts it, you get inconsistency the moment data arrives from anywhere other than typing.
A compact comparison of the filtering layers
| Layer | Catches | Misses | Best for |
|---|---|---|---|
| PreviewTextInput | Single typed characters, prospective length | Paste, drop, programmatic set, IME edge cases | Immediate feedback on alphabet |
| DataObject.Pasting | Pasted text | Typing, programmatic set | Bulk input control |
| TextChanged / full-string check | Any text change including undo | Values set before handler attach | Positional and range rules |
| Binding validation | Model-sourced and UI-sourced values | Values never bound or submitted elsewhere | Single source of truth |
| Save/submit guard | Everything reaching persistence | Nothing, if it is truly the last gate | Data safety |
Read the table as a division of labor, not a menu. Each row is cheap to add and closes a specific gap; the submit guard is the one you cannot omit even if every other layer is present, because future code paths—imports, tests, API calls—will bypass the UI eventually.
Common failure cases and how to diagnose them
Paste still inserts invalid text. The Pasting handler isn't attached, or it's attached to the wrong element (for example, a TextBox inside a template whose handler was wired on the template root). Check that the event is registered per instance, and confirm with a breakpoint that it fires.
Typing works but IME input breaks. Per-character filtering interacts badly with composition. Symptom: characters from an East Asian IME vanish or arrive out of order. Fix: relax PreviewTextInput to allow the composition characters and rely on the full-string check.
Decimal point rejected in some locales. The handler hard-codes . while parsing uses a different culture. Symptom: certain users can paste but not type the separator, or vice versa. Fix: read separators from the same CultureInfo used for parsing, and test with at least one comma-decimal culture.
Text reverts while typing. A TextChanged handler is reassigning Text to the last valid value. This resets the caret and breaks undo. Fix: stop correcting; show validation state and validate at submit.
Undo produces invalid text. Full-string validation wasn't wired to TextChanged, so Ctrl+Z restores a rejected earlier state. Fix: validate on the resulting text, not on the input event, so every path is covered.
Negative numbers impossible to type. The sign is rejected because the predicate checks only digits. Fix: allow the culture's negative sign at position zero in the prospective string, and let parsing confirm it.
Values fail at the database but pass the UI. The UI filter and the persistence-layer rule disagree—typically over trimming, casing, or Unicode normalization. Fix: reuse one shared validation component, and normalize consistently (for example, String.Normalize for identifiers) at a single defined point.
The stop condition for self-repair: if fixing one field's rule requires changing parsing, persistence, or a shared model, treat it as a cross-cutting change and get it reviewed rather than patching the event handler locally. That's how filters drift out of sync.
A worked edge case: the paste-from-spreadsheet problem
Suppose a user copies a column of prices from a spreadsheet into the decimal field. Spreadsheet copy typically delivers tab-separated text with a trailing newline—something like 12.50\t13.75\t9.99\r\n. A whole-paste rejection blocks it entirely, which may be what you want if the field holds one value, but it's unhelpful if the user expected the first cell to land. A sanitizing handler that strips everything after the first line break, trims white space, and then validates the remainder gives a predictable result: the first value is inserted if valid, otherwise the paste is refused.
Whichever behavior you choose, document it in the field's tooltip, because paste behavior that isn't announced feels like a bug. And test the paste path explicitly—it's the single most common way invalid characters enter a "filtered" TextBox.
Matching culture, type, and persistence so the rule holds end to end
The deepest source of trouble is a mismatch between three definitions of "valid": what the user sees, what the app parses, and what the database stores. Align them deliberately:
Choose one culture for parsing and formatting per field. For localized user-facing fields, use CultureInfo.CurrentCulture. For codes, keys, and interchange formats, use CultureInfo.InvariantCulture. Never parse with one and format with the other. Decide how empty and partial states behave. An empty optional field is valid; a required field's empty state is valid-to-edit but invalid-to-submit. Encode that distinction in the validation component rather than the event handlers. Normalize once. If identifiers are case-insensitive or accent-insensitive in storage, define where normalization happens—typically in the submit guard—and keep the UI rule about characters, not about normalization. Guard the boundary. Even with perfect UI filtering, validate in the service or repository layer that persists the value. This is the check that survives refactoring of the view.
When those three definitions agree, the question "how do I avoid invalid characters" reduces to one predicate reused everywhere, with keystroke and paste handlers acting as early, friendly copies of it. When they disagree, no amount of event handling will keep bad data out, because the definition itself is inconsistent.
FAQ
Does MaxLength on the TextBox replace a character filter? No. MaxLength limits the number of characters but says nothing about which ones; it also interacts with paste and international text unpredictably. Use it for length caps and a predicate for alphabet and format.
Should I use a masked TextBox instead? A masked control enforces a fixed shape, which suits phone numbers and dates but is rigid for free-form numeric entry. If your rule is genuinely positional, a mask or a dedicated numeric control can reduce handler code; if the rule is "a parseable number," full-string parsing is simpler and more forgiving.
Why not just catch the parse exception on submit? You can, and you should keep that guard. But catching at submit gives the user no early feedback and lets a whole session of invalid typing go unnoticed. The layered approach is about when the user learns, not whether the boundary is checked.
Is char.IsDigit safe for numeric fields? It accepts digits from many scripts, which is usually right for display but may not match an ASCII-only parser. Decide which you mean and test with a non-ASCII numeral; char.IsAsciiDigit (available on modern .NET) or an explicit range check gives the stricter behavior.