0

I've worked on a little console application in C# to get started with the language. My goal is to ask the following from user:

  • First name
  • Surname
  • Year of birth
  • Month of birth
  • Day of birth

I have made all of the input fields like following:

System.Console.Write("Name: ");
String name = System.Console.ReadLine();

In the end, the application saves the data to a .txt file, if the given data is valid. I need to check if the length of the name fields is between 1-30, and that the date inputs only accept numeric answers within their corresponding limitations (for e.g: You can only give 'month' a value between 1-12..)

I've tried to search for different validating methods, but I do not know how to throw them all together and make a clean "Checker" -part for this application.

This is what validated my first and last name fields, but I don't think you can put the date fields to the same checkup?

public static Boolean Checker(String check)
{
   if (check.Length <= 30 && check.Length > 0)
   {
      return true;
   }
   return false;
}

Any advice?

11
  • 1
    Can you use regex - regular expression? Commented Jul 7, 2016 at 7:27
  • do you want to have one method to check all user input parameters? or one for each? Commented Jul 7, 2016 at 7:29
  • 1
    Validation of dates, numbers and strings cannot be resolved without knowing what that string represents Commented Jul 7, 2016 at 7:29
  • @MongZhu Preferably one method, since it would be easier to then run the .txt file writing if the only condition is if the checker returns true. Commented Jul 7, 2016 at 7:30
  • 3
    I would first use int.TryParse() on each input (year, month, day) and will fail immediately in case any of those are not actually a number. Then checks if the value falls within a valid range (1-30, 1-12, 1-2016) and only then will try to check for the actual validity of the date using DateTime.TryParse() Commented Jul 7, 2016 at 7:33

3 Answers 3

1

You can't reasonably validate these inputs inside a single method without knowing what that strings represents.

First of all I suggest you to ask input only for a date and not for three separate values. It is a lot easier to validate the date input as a single value instead of three separate values. The NET library offers an many methods to parse a date with a single call (DateTime.TryParse, DateTime.TryParseExact). Instead, having three separate inputs, requires you to duplicate the logic to check for leap years, check for the last day of month and many other subtle aspects of dates caused by localization issues.

So, I suppose that you ask just for firstname, surname and date of birth and you change your validation to

public static Boolean Checker(String check, bool isDate)
{
   if(isDate)
   {
       DateTime dt;
       // Here you could add your formatting locale as you find appropriate
       return DateTime.TryParse(check, out dt); 
   }
   else
       return check.Length > 0 && check.Length <= 30;
}

In this way your input whould be something like this

// Infinite loop until you get valid inputs or quit
for(;;)
{
    System.Console.Write("Name: ('quit' to stop)");
    String name = System.Console.ReadLine();
    if(name == "quit") return;

    if(!Checker(name, false))
    {
         // Input not valid, message and repeat
         Console.WriteLine("Invalid name length");
         continue;
    }


    System.Console.Write("Date of Birth: (quit to stop)");
    String dob = System.Console.ReadLine();
    if(dob == "quit") return;

    if(!Checker(dob, true))
    {
         // Input not valid, message and repeat
         Console.WriteLine("Invalid name length");
         continue;
    }
    // if you reach this point the input is valid and you exit the loop
    break;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This seems promising. I've changed my date input to one field only. But how can I use this return value in the file-writing part? Right now, the if is if (Checker(true)){ --- Write to text file --- } but it does not seem to work. Ideas?
Got it working like a charm! I added the file-write part just before the break and also changed it so that the program must be closed by pressing any key (instead of an automatic shutdown). I did not figure out how to write the file in DD;MM;YYYY format, but I'll be fine with DD.MM.YYYY too. Thanks a bunch!
0

In order to check if input string is date, you can try to parse it into DateTime object:

            DateTime date;
            if (!DateTime.TryParseExact(inputString, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None, out date))
            { 

            }

3 Comments

This will throw an exception in case of invalid input. Also, the OP is gathering birth date using 3 different inputs (year, month, day), your solution would have to reflect that.
Yes, I tried to solve the problem yesterday with just one "date of birth" field, but I have now separated the fields to 3 different ones, since I can more easily confirm the month/day can't be messed upside down.
You're right, i used ParseExact instead of TryParseExact. I replaced it. @ProDexorite, you can set the format as you wish in order to supprort some more varients of datetime formats. the TryParseExact is overloaded with string[] where you can put in several formats
0

You should have a central method that creates a User-object from the input if it was valid and one method to check every input type like FirstName or DayOfBirth. For example:

public class User
{
    public static User CreateUserFromText(string firstName,string surName,string yearBirth,string monthBirth,string dayBirth)
    {
        if (firstName == null || surName == null || yearBirth == null || monthBirth == null || dayBirth == null)
            throw new ArgumentNullException(); // better tell what argument was null

        User user = new User
        {
            FirstName = firstName.Trim(),
            SurName = surName.Trim()
        };
        bool validInput = IsFirstNameValid(user.FirstName) && IsSurNameValid(user.SurName);
        DateTime dob;
        if (!validInput || !IsValidDayOfBirth(yearBirth, monthBirth, dayBirth, out dob))
            return null;
        user.DayOfBirth = dob;
        return user;
    }

    public DateTime DayOfBirth { get; set; }

    public string SurName { get; set; }

    public string FirstName { get; set; }

    private static bool IsFirstNameValid(string firstName)
    {
        return firstName?.Length >= 1 && firstName?.Length <= 30;
    }

    private static bool IsSurNameValid(string surName)
    {
        return surName?.Length >= 1 && surName?.Length <= 30;
    }

    private static bool IsValidDayOfBirth(string year, string month, string day, out DateTime dayOfBirth)
    {
        DateTime dob;
        string dateStr = $"{year}-{month}-{day}";
        bool validDayOfBirth = DateTime.TryParse(dateStr, out dob);
        dayOfBirth = validDayOfBirth ? dob : DateTime.MinValue;
        return validDayOfBirth;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.