Sunday, October 23

Characters Validation in Name field using C-sharp Language

The following program is to validate name field. There is a methods which is user defined named as checkEntry which is taking string as an argument. In this method a loop is used which is starting from 0 to string length. Code is pretty simple and anyone can understand it very easily. You will some useless variable and class in this code. You do not need to create another class and user defined method. This can be done in main method. Copy code from user defined method and paste it in main method and handle this in a loop as per requirement i have used 'while' loop here.



/////////////////////////////////////////////////////////////////////////// Begins /////////////////////////////////////////////////////////////////////////////

    class checkName {
        public int checkEntry(string name)
        {
            int flag = 0, countChar = 0;

//loop is used to check characters in the string 
            
for (int i = 0; i < name.Length; i++)
            {
                if (char.IsLetter(name[i]) || name[i] == '.' || name[i] == ',')
                {
                    countChar++;
// static method isLetter is to check whether character is alphabet or numeric 
                    if (countChar == name.Length) // if this condition gets true it means that there is no invalid entry in name field
                    {
                        flag = 1; // set value of flag to 1
                        break; //break from the loop
                    }
                }
            }
            if (flag == 1)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string name;
            checkName obj = new checkName();
            do // do while loop is handled because it is run for at least one time
            {
                Console.Write("Enter Valid Name: ");
                name = Console.ReadLine();
            }
            while (obj.checkEntry(name) == 0);
// It will remain stuck into loop when checkEntry returns 0 value
            Console.Write("Your Valid Name: "+name);
            Console.ReadLine();
        }
    }

/////////////////////////////////////////////////////////////////////////// Ends ////////////////////////////////////////////////////////////////////////////////

No comments:

Post a Comment