Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic user-input string validation

Tags:

c#

validation

I have been writing a check in a name property of my person abstract class. The problem that i have is that i am trying to implement a piece of code that will not allow the user to leave the field empty or to exceed the name limit with 35characters or in-put a digit but i am stuck with it. If any one can help or suggest me.

    public string Name
    {
        get { return name; }

        set 
        {
            while (true)
            {
                if (value == "" || value.Length > 35)
                {
                    Console.Write("Please Enter Correct Name: ");
                    value = Console.ReadLine();
                    continue;
                }

                foreach (char item in value)
                {                        
                    if (char.IsDigit(item))
                    {
                        Console.Write("Digits Are NotAllowed....\n");
                        Console.Write("Please Enter Correct Name: ");
                        value = Console.ReadLine();
                        break;
                    }
                }
                break;
            }
            name = value;                
        }
    }
like image 232
Sarfraz Amjad Avatar asked Sep 28 '11 17:09

Sarfraz Amjad


1 Answers

From a semantics point of view, a setter is as its name says, a setter! It should be used to set a private/protected field of a class From a testability point of view, your design is very hard to be automatically tested not to say impossible!

This reminds me of a bit of code I worked on sometime ago where a setter is opening a socket and sending stuff over the network! The code should do what it reads, just imagine if someone uses your code, calls your setter and wonders why on earth does his/her application hang (waiting for user input)

The way I see your code more readable and testable is to have a verifer class that ensures the user is entering the right data in the right format. The verifier should take an input stream as data source, this will help you easily test it.

Regards,

like image 109
GETah Avatar answered Sep 28 '22 16:09

GETah