如何验证从 Request.From[""] 收到的数据

How to verify data received from Request.From[""]

我正在尝试验证用户写入的数据。如果数据写入不正确 (dd/MM/yyyy),应用程序将无法运行。任何想法如何做到这一点?示例:日期格式是否正确,文本框是否为空等。 这是我的观点:

@using (Html.BeginForm("About", "Home"))
{
    <label for="datePicker">Type in a date:</label>

    @Html.TextBox("datePicker", @DateTime.Now.ToString("dd/MM/yyyy"), new { id ="datePicker" })
    <br />
    <br />
    <label for="datePickerStart">Type in starting date:</label>
    @Html.TextBox("datePickerStart", @DateTime.Now.ToString("dd/MM/yyyy"), new { id ="datePickerStart" })
    <br />
    <br />
    <label for="datePickerEnd">Type in ending date:</label>
    @Html.TextBox("datePickerEnd", @DateTime.Now.ToString("dd/MM/yyyy"), new { id ="datePickerEnd" })
    <br />
    <input id="submitBtn" type="submit" value="Search" class='create__btn create__customBtn' />
    <a asp-action="About">Refresh</a>
}
<p>Money earned for the selected date: @ViewBag.SelectedDateSum RON</p>
<p>Money earned in the time period selected: @ViewBag.BetweenSum RON</p>
</div>

还有我的控制器:

public ActionResult About(DateTime? datePicker)
        {
            DateTime userSelectedDate = DateTime.ParseExact(Request.Form["datePicker"].ToString(), "dd/MM/yyyy", null);
            
            //value for a selected date
            var allInvoices = _context.Invoices.Where(dd => dd.IssuedDate == userSelectedDate).ToArray();
            int sumFirst = 0;
            foreach (var invoice in allInvoices)
            {
                int x = Int32.Parse(invoice.Value);
                sumFirst += x;
            }
            ViewBag.SelectedDateSum = sumFirst;

            //value between two selected dates
            DateTime startDate = DateTime.ParseExact(Request.Form["datePickerStart"].ToString(), "dd/MM/yyyy", null);
            DateTime endDate = DateTime.ParseExact(Request.Form["datePickerEnd"].ToString(), "dd/MM/yyyy", null);
            int sumBetween = 0;
            var allInvoices1 = _context.Invoices.Where(dd => dd.IssuedDate >= startDate && dd.IssuedDate <= endDate).ToArray();
            foreach (var invoice in allInvoices1)
            {
                int x = Int32.Parse(invoice.Value);
                sumBetween += x;
            }
            ViewBag.BetweenSum = sumBetween;

            return View();
        }

使用 DateTime.TryParse() instead. If it returns false, then call ModelState.AddError() 和 return 模型视图。您可以使用验证器在视图中调出错误表单。

我建议使用 TryParseExact 而不是 ParseExact。您可以通过这种方式在后端捕获格式错误的用户输入:

public ActionResult About(DateTime ? datePicker) {
    DateTime userSelectedDate;
    //value between two selected dates
    DateTime startDate;
    DateTime endDate;
if (DateTime.TryParseExact(Request.Form["datePicker"].ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out userSelectedDate)
        && DateTime.TryParseExact(Request.Form["datePickerStart"].ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out startDate)
        && DateTime.TryParseExact(Request.Form["datePickerEnd"].ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out endDate))
    {
    //value for a selected date
    var allInvoices = _context.Invoices.Where(dd => dd.IssuedDate == userSelectedDate).ToArray();
    int sumFirst = 0;
    foreach (var invoice in allInvoices)
    {
        int x = Int32.Parse(invoice.Value);
        sumFirst += x;
    }
    ViewBag.SelectedDateSum = sumFirst;


    int sumBetween = 0;
    var allInvoices1 = _context.Invoices.Where(dd => dd.IssuedDate >= startDate && dd.IssuedDate <= endDate).ToArray();
    foreach (var invoice in allInvoices1)
    {
        int x = Int32.Parse(invoice.Value);
        sumBetween += x;
    }
    ViewBag.BetweenSum = sumBetween;

    return View();
} else
{
    //Malformed date was provided
    
}
}

尝试解析 DateTime 文档:https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-6.0

Int32等数据类型也支持TryParse:https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0

也有提供验证 front-end 的指南,但诚然,这不是我的强项: https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/validating-user-input-in-aspnet-web-pages-sites