簡體   English   中英

如果-否則檢查所有字符串值(長度,為數字)

[英]If-else check for all string values (length, is numeric)

我已經使用C#開發了一個小型控制台應用程序,以開始使用該語言。 我的目標是向用戶提出以下要求:

  • 名字
  • 出生年份
  • 出生月份
  • 出生日期

我已經完成了所有的輸入字段,如下所示:

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

最后, 如果給定數據有效 ,則應用程序會將數據保存到.txt文件。 我需要檢查名稱字段的長度是否在1到30之間,並且日期輸入僅在其相應限制內接受數字答案(例如:您只能為“ month”賦予1到12之間的值。)

我試圖搜索不同的驗證方法,但是我不知道如何將它們全部組合在一起,並為此應用程序制作一個干凈的“ Checker” -part。

這是驗證我的名字和姓氏字段的方法,但是我認為您不能將日期字段進行相同的檢查?

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

有什么建議嗎?

在不知道字符串代表什么的情況下,您無法在單個方法中合理地驗證這些輸入。

首先,我建議您僅要求輸入一個日期,而不要求三個單獨的值。 將日期輸入驗證為單個值而不是三個單獨的值要容易得多。 NET庫提供了許多方法,可以通過一次調用來解析日期( DateTime.TryParseDateTime.TryParseExact )。 相反,具有三個單獨的輸入,需要您重復邏輯以檢查leap年,檢查月份的最后一天以及由本地化問題引起的日期的許多其他細微方面。

因此,我想您只要求輸入名字,姓氏和出生日期,然后將驗證更改為

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;
}

這樣,您的輸入可能是這樣的

// 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;
}

為了檢查輸入字符串是否為日期,您可以嘗試將其解析為DateTime對象:

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

            }

您應該有一個中央方法(如果有效)從輸入創建一個User object,以及一個檢查每個輸入類型(如FirstNameDayOfBirth 例如:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM