C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » General »

Validating text boxes for alphabetic and numeric inputs


Posted Date: 05 Apr 2004    Resource Type: Articles    Category: General
Author: rohit vermaMember Level: Bronze    
Rating: 1 out of 5Points: 7



In .NET, there is no builtin function available to check if the given value is a valid number or not. One option is to iterate through each character in the string and check if the given string contains all digits or not.

The following sample iterates through all characters and if all are digits return TRUE. If any character is not a digit, it returns false.

Note that the given sample doesn't consider 'period'. So, 12.25 will be invalid, according to the following samples. You may need to add additional validation to include the period and make sure there is no more than one period.

VB.NET sample :

Private Function ValidateNumber(ByVal input As String) As Boolean
Dim c As Char
For Each c In input
If Not Char.IsNumber(c) Then
Return False
End If
Next

Return True
End Function


C# sample :

private bool ValidateNumber(string input )
{
foreach ( char c in input )
{
if ( ! Char.IsNumber( c ) )
{
return false;
}
}

return true;
}


Another inefficient, but easy method many programmers follow is,

Try
Dim val As Int32 = TextBox1.Text
Catch ex As InvalidCastException
MessageBox.Show("Given value is not a valid 'Int'.")
End Try

Try
Dim val As Double = TextBox1.Text
Catch ex As InvalidCastException
MessageBox.Show("Given value is not a valid 'Double'.")
End Try


The above method will work perfect to check any datatype, but depending on exception to check is not a reccommended approach.




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: How to create new project templates for Visual Studio .NET
Previous Resource: Model View Controller (MVC ) Architecture
Return to Discussion Resource Index
Post New Resource
Category: General


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use