How to allow only number input in your code using C#

Being coder, we often have different challenges to write code to accomplish a task based on some exact requirement. Here we are going to learn how to allow the user only to write number not other characters like “a/A to z/Z” and other special characters like “!@#$%^&*()-+.,?:;'”.
how allow user only to write number in C#

 You can use below code to check input value is completely number or not

 

Let us see what actually str.All(char.IsDigit) do

  • str is user entered value stored in string type variable str.
  • All is bool function in an Enumerable class of System.Linq namespace
  • char.IsDigit checking each and every character of str whether it is Digit or not. If there is no found any nondigit value it will return true otherwise it will return false.

Now to test “IsValidNumber” function, let us create a console application and use below code

 

After going through the code, you might be thinking what actual DispHint(strValue) is ? Go through below code to see why and how created DispHint() function.

 

In DispHint() function, we are actually using Regex class to extract only number from values entered by user.

To Use Regex class, you have to use System.Text.RegularExpressions namespace first.

Complete Code –

 

There are many ways through which you can perform the same task. Please post your code in a comment and let novice coder know how to perform the task in different ways. Your all suggestions are most welcome and appreciated. Happy Coding !!

One thought on “How to allow only number input in your code using C#”

  1. BestEllis says:

    I have noticed you don’t monetize your website, don’t waste your
    traffic, you can earn additional bucks every month because you’ve got hi quality content.
    If you want to know how to make extra $$$, search for: Ercannou’s essential
    adsense alternative

Leave a Reply