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

Being coder, we often have different challenges to write code to accomplish task based on some exact requirement. Here we are going to learn how to allow 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

  public static bool IsValidNumber(string str)
        {
           return str.All(char.IsDigit);
        }

// IsValidNumber("123456") - return true 
// IsValidNumber("123456abc") - return false
// IsValidNumber("123.45") - return false

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 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 non digit 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

 ask: Console.WriteLine("Enter your number: ");
            string strValue = Console.ReadLine();
            bool valid = false;
            while(!valid)
            {
                valid = IsValidNumber(strValue);
                if (!valid)
                {
                    Console.WriteLine("Invalid Entry..." + DispHint(strValue));         
                    goto ask;
                }
            }
            Console.WriteLine("you have entered : " + strValue);

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.

  public static string DispHint(string str)
        {
            string[] numbers = Regex.Split(str, @"\D+");
            string hintmsz = "";
            foreach (string value in numbers)
            {
                if (!string.IsNullOrEmpty(value))
                {
                    hintmsz = "Valid Number are : "+ int.Parse(value)+" , please remove rest.";
                }
            }
            return hintmsz;
        }

// DispHint("123456abc"); -  Valid Number are : 123456 , please remove rest.

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 –

 class Program
    {
        public static string DispHint(string str)
        {
            string[] numbers = Regex.Split(str, @"\D+");
            string hintmsz = "";
            foreach (string value in numbers)
            {
                if (!string.IsNullOrEmpty(value))
                {
                    hintmsz = "Valid Number are : "+ int.Parse(value)+" , please remove rest.";
                }
            }
            return hintmsz;
        }
        public static bool IsValidNumber(string str)
        {
           return str.All(char.IsDigit);
        }
        public static void Main()
        {           
            ask: Console.WriteLine("Enter your number: ");
            string strValue = Console.ReadLine();
            bool valid = false;
            while(!valid)
            {
                valid = IsValidNumber(strValue);
                if (!valid)
                {
                    Console.WriteLine("Invalid Entry..." + DispHint(strValue));         
                    goto ask;
                }
            }
            Console.WriteLine("you have entered : " + strValue);
            Console.ReadLine();
        }
    }

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

Share Knowledge
This entry was posted in C#, TIPS/TRICKS and tagged , , , , . Bookmark the permalink.

One Response to 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

Your email address will not be published. Required fields are marked *