One major caveat I have seen a lot and even here on CodeProject, when people are talking about validating entries in a TextBox is that, they often forget all sorts of combinations of Cut/Copy/Paste. Ctrl+V is the most often checked for and sometimes they apply custom copy/paste context menus.
One thing I love about the default context menus is that they are language independent, so if you don’t mess with them, they are valid all around the world. The other things I have seen often missed are Ctrl-Insert and Shift-Insert (ctrl – copy, shift - paste) consideration. If you didn’t know try them out. Those are combinations that often work in high profile apps as well even if the coders wanted to shut off copy and paste (even Microsoft in some cases).
You just could use the
TextChanged event but that’s real annoying, especially if you bind a data provider of any sort to the text box. So much unnecessary validation…
So what to do, you want to check the entry, you don’t want to lose the nice default context menu and you want to check for any cut, paste, undo (don’t forget undo) and you don’t want to do unnecessary validation. It is so easy you won’t believe it :).
Public Class TextBoxExtended
Private Const WM_PASTE As Integer = &H302
Private Const WM_CUT As Integer = &H300
Private Const WM_UNDO As Integer = &H304
Public Event CheckMe()
Public Sub New()
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Select Case m.Msg
Now just do your validation in the
CheckMe event and the default
KeyUp event of the
A small Update
To illustrate why this approach can be interesting (thanks mav.northwind) I updated this article with a small demo. In the demo, a valid entry is something like “xyz = 123” and if it is not of that type, it tells the user what the problem is (hover over the exclamation mark).
It uses a
Regex to do the validation and an
ErrorProvider to inform the user, so the concept should be easily adaptable to more “Real World” needs.
If you download the source, you have to run the application once before the control shows up in the designer. To simplify it, I changed the generated code.