![]() |
| | #1 |
| Registered User Join Date: Jun 2009
Posts: 21
| Checking against regular expression on KeyPressEvent I'm trying to put something together that validates a textbox against a regular expression that defines currency, so on each key press, if the text does not match a valid currency amount it handles that key press. Here's the code i'm using: Code: private void InputMoney(KeyPressEventArgs e, string s)
{
if (!Regex.IsMatch(s, @"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$"))
{
e.Handled = true;
}
Thanks. Last edited by scott_ill; 10-26-2009 at 11:16 AM. |
| scott_ill is offline | |
| | #2 |
| Registered User Join Date: Jun 2009
Posts: 21
| By the way, I nabbed the regular expression from regexlib.com, and it should "Match currency input with or without commas." |
| scott_ill is offline | |
| | #3 |
| Registered User Join Date: Jan 2008
Posts: 276
| Suppose you typed 01 into the textbox. If you then entered a decimal point '.' the exact text contained in the textbox would be "01.", which is not valid according to your regular expression. You might try tweaking the regex a bit: Code: Instead of:
@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$"
Maybe:
@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9]{0,2})?$"
^---------^
As an alternative, instead of handling the key event and preventing the text from being entered, you might instead change the background color of the textbox to a color that indicates an error (Color.MistyRose maybe?) Then, in the future, you don't have to worry about a complicated regular expression locking out your ability to type in a valid string. Sometimes you may have to type in something invalid in order to get to a valid state. If, for example, you were to try the same approach with a phone number it probably wouldn't work. Surely you have to type something like "(368)" before you continue entering the rest of the phone number, but that obviously isn't a valid phone number on its own. You might also want to look at the MaskedTextBox, which can do the same thing, only it doesn't use regular expressions. |
| arpsmack is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Buidl Library with ./configure script | Jardon | C Programming | 6 | 07-24-2009 09:36 AM |
| Profiler Valgrind | afflictedd2 | C++ Programming | 4 | 07-18-2008 09:38 AM |
| Screwy Linker Error - VC2005 | Tonto | C++ Programming | 5 | 06-19-2007 02:39 PM |
| Problems about gcc installation | kevin_cat | Linux Programming | 4 | 08-09-2005 09:05 AM |
| Please Help - Problem with Compilers | toonlover | C++ Programming | 5 | 07-23-2005 10:03 AM |