Home > Back-end >  How to verify data received from Request.From[""]
How to verify data received from Request.From[""]

Time:05-26

I'm trying to verify a data written by the user. If the data is not written correctly (dd/MM/yyyy), the application doesn't work. Any ideas how to do that? Examples: if the date format is the correct, if the text box is empty etc. Here is my View:

@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>

And my controller:

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

CodePudding user response:

Use DateTime.TryParse() instead. If it returns false, then call ModelState.AddError() and return the view with the model. You can use validators to call out the error form there in the view.

CodePudding user response:

I would recommend using TryParseExact rather than ParseExact. You can catch malformed user input on the backend this way:

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

Try Parse DateTime Docs: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-6.0

Int32 and other datatypes also support TryParse: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0

There are also guides to provide validation on the front-end but admittedly that isn't my forte: https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/validating-user-input-in-aspnet-web-pages-sites

  • Related