Friday, February 8, 2008

How to completely validate input in a TextBox even on paste

I had a textbox and I wanted to make sure that the text entered was only alpha numeric.  I put in validation logic in to KeyPress which you can find just by doing a google search.  However, most of the sample code out there limits the data as you enter it, one character at a time.  What if you want to allow people to paste text into your textbox, and still validate the data pasted.

The solution was to put validation logic into the TextChanged event as well.  I don't remember exactly the scenario, but there might be situations where your validation logic my interpret the Ctrl-V as an invalid character, and it won't allow you to paste your values in.  The way I was able to work around this was in the KeyDown event to check if the Ctrl button was pressed, if it was pressed, I would set a flag.  In the KeyPress event I checked if the flag was set.  If it was set, then I didn't go into my validation logic (which would have interpreted the Ctrl-V as an invalid character), I just exited the sub.  This way the text was pasted, but in TextChanged, I would then validate the text that was pasted.

No comments: