Click here to Skip to main content
15,903,728 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ALL
How could i validate a textbox in vb.net WINDOWS FORM, so that it disallow only two punctuation character that is "," and "."
Posted
Updated 27-Feb-11 20:10pm
v3
Comments
coolestCoder 28-Feb-11 1:12am    
What environment you are talking about ? ASP.Net or Windows Forms ?
IndrajitDasgupat 28-Feb-11 1:29am    
Windows Forms

Use a regular expression validator
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 28-Feb-11 2:04am    
Mark, this is correct answer, my 5, but in this simple case filtering out unwanted characters is much better; please see my answer.
--SA
[no name] 28-Feb-11 7:30am    
One or two characters maybe but soon you end up with a long list (hopefully not if statements) to check where a RegEx will check all at once.
Sergey Alexandrovich Kryukov 28-Feb-11 11:32am    
Absolutely agree. But if characters can be filtered, they should be filtered, even if validation is ultimately used. Why creating an extra source of user's mistake?

At the same time, if filtering is a bit more complex (such as position or context depended as some tried to do in effort to enforce valid floating-point with exponent and two signs (bad idea!)), then filtering would be too confusing the the user and should not be used.

--SA
If the only constraint is to disallow punctuation character, validation is not needed. It's better to filter out key presses to ignore unwanted characters in first place, from input. For this purpose:

1) Handle TextBox.KeyPress event;

2) In event handler, get KeyChar from event argument and figure out if this character should be filtered out, in this case, assign event argument's Handled to true.

3) The method char.IsPunctuation(char) helps to classify punctuation characters.

I tested it in code before posting this Answer.

—SA
 
Share this answer
 
v2
Comments
IndrajitDasgupat 28-Feb-11 2:08am    
No it disallow only two punctuation character that is "," and "."
Sergey Alexandrovich Kryukov 28-Feb-11 11:29am    
What do you mean "no"? This is the same thing. You just compare KeyChar (which is char) with '.' and ',', instead of using item (3). That's why I explained more general case in (2); because I knew there can be variants of the check. Just do it, I tested and make sure it works correctly.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900