Click here to Skip to main content
15,886,783 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a windows form in c# ,in that for textbox I want to apply validation i.e Only to enter the text or to enter only numeric values.
please help me in this.

Thanks in Advance.
Posted
Updated 20-May-11 2:33am
v5
Comments
ZeeroC00l 19-May-11 4:42am    
--edited for format and grammar
BR//
Harsha

That's good you mention Javascript. It's the best to do it on the client side, as the events you have to consume are too frequent.

Here is how:
HTML
<html>
   <head>
      <script type="text/javascript"><!--
         function filterDigits(eventInstance) { 
            eventInstance = eventInstance || window.event;
                key = eventInstance.keyCode || eventInstance.which;
            if ((47 < key) && (key < 58) || key = 45 || key == 8) {
               return true;
            } else {
                    if (eventInstance.preventDefault) eventInstance.preventDefault();
                    eventInstance.returnValue = false;
                    return false;
                } //if
         } //filterDigits
      --></script>
   </head>
<body">

<input type="text" onkeypress="filterDigits(event)"/>

</body>
</html>


Pay attention that backspace is also allowed. By some historical reasons backspace is considered a character and should be allowed anyway.

—SA
 
Share this answer
 
v2
Comments
[no name] 20-May-11 8:34am    
Good Call SA. My 5 too.
Sergey Alexandrovich Kryukov 20-May-11 23:50pm    
Thank you, Ramalinga.
--SA
Chil Umez 20-May-11 8:38am    
He created a windows form in c#. not asp page
Sergey Alexandrovich Kryukov 20-May-11 23:51pm    
Why do you thinks so? Read the tag: Javascript. Period.
Ah, "Form" in text. I don't care. This is OP's fault.
--SA
Wonde Tadesse 20-May-11 8:53am    
Good answer. My 5:)
Firt the tag you've used in confusing. Are you talking about winforms or ASP.Net as you say C# and JavaScript.
If you are looking for ASP.Net validations, see here[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 19-May-11 13:47pm    
If it's numeric-only, it should practically always filtering, not validation, and only in Javascript. Validation can be added at the server side as well. OP needs the tag ASP.NET.

I explain it in my answer, please see.
Wonde Tadesse 20-May-11 8:55am    
Please see --SA answer. It is not only validation,it has to be filtered except numbers.
In keypress event check each key with char.IsDigit and decide what to do.
 
Share this answer
 

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