【问题标题】:If-else check for all string values (length, is numeric)if-else 检查所有字符串值(长度,是数字)
【发布时间】:2016-07-07 17:07:23
【问题描述】:

我使用 C# 编写了一个小型控制台应用程序以开始使用该语言。我的目标是向用户询问以下内容:

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

我已将所有输入字段设置如下:

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

最后,应用程序将数据保存到 .txt 文件中,如果给定的数据有效。我需要检查名称字段的长度是否在 1-30 之间,并且日期输入仅接受其相应限制内的数字答案(例如:您只能为 'month' 提供 1-12 之间的值..)

我尝试搜索不同的验证方法,但我不知道如何将它们组合在一起并为此应用程序创建一个干净的“检查器”部分。

这是验证我的名字和姓氏字段的原因,但我认为您不能将日期字段放在同一个检查中?

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

有什么建议吗?

【问题讨论】:

  • 你能用regex - 正则表达式吗?
  • 您想要一种方法来检查所有用户输入参数吗?还是每个人一个?
  • 在不知道字符串代表什么的情况下无法解析日期、数字和字符串的验证
  • @MongZhu 最好是一种方法,因为如果唯一的条件是检查器返回true,那么运行.txt文件写入会更容易。
  • 我会首先在每个输入(年、月、日)上使用int.TryParse(),如果其中任何一个实际上不是数字,则会立即失败。然后检查该值是否在有效范围内(1-30、1-12、1-2016),然后才会尝试使用DateTime.TryParse()检查日期的实际有效性

标签: c# console-application


【解决方案1】:

在不知道字符串代表什么的情况下,您无法在单个方法中合理地验证这些输入。

首先,我建议您只要求输入日期而不是三个单独的值。将日期输入验证为单个值而不是三个单独的值要容易得多。 NET 库提供了许多方法来通过单个调用解析日期(DateTime.TryParseDateTime.TryParseExact)。相反,拥有三个单独的输入需要您复制逻辑来检查闰年、检查月份的最后一天以及由本地化问题引起的日期的许多其他细微方面。

所以,我想您只要求输入名字、姓氏和出生日期,然后您将验证更改为

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

【讨论】:

  • 这看起来很有希望。我已将日期输入更改为仅一个字段。但是如何在文件写入部分使用这个返回值呢?现在,if 是if (Checker(true)){ --- Write to text file --- },但它似乎不起作用。想法?
  • 让它像魅力一样工作!我在break 之前添加了文件写入部分并对其进行了更改,以便必须通过按任意键关闭程序(而不是自动关闭)。我不知道如何以 DD;MM;YYYY 格式编写文件,但我也可以使用 DD.MM.YYYY。非常感谢!
【解决方案2】:

为了检查输入字符串是否为日期,您可以尝试将其解析为 DateTime 对象:

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

            }

【讨论】:

  • 这会在输入无效的情况下抛出异常。此外,OP 正在使用 3 个不同的输入(年、月、日)收集出生日期,您的解决方案必须反映这一点。
  • 是的,我昨天尝试只使用一个“出生日期”字段来解决问题,但我现在已将这些字段分成 3 个不同的字段,因为我可以更轻松地确认月份/日期不要颠倒过来。
  • 你说得对,我使用 ParseExact 而不是 TryParseExact。我把它换了。 @ProDexorite,您可以根据需要设置格式,以支持更多的日期时间格式。 TryParseExact 用 string[] 重载,您可以在其中放入多种格式
【解决方案3】:

你应该有一个中心方法,如果它是有效的,则从输入创建一个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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2022-12-01
    • 2010-09-05
    相关资源
    最近更新 更多