0
votes

I have a model with a nullable DateTime property.

The date does not need to be entered, hence the nullable type. If it IS entered, though, it should be validated to lie forward in time.

Using Remote Validation on the property however, always gives null as an in-parameter in my validation method, even if the datepicker-field contains a value using the correct format. How can I get it to try the value from my input field?

The datepicker calender is limited to not be able to pick past dates. But you are still able to input a date manually. Doing so triggers the validation but always with a null value as in-parameter. I have a similar function where the DateTime is not nullable and it works correctly.

MODEL

[Remote("CheckDateNotInPast", "Validation", ErrorMessage = @"The date must lie forward in time.")]
        public DateTime? Deadline { get; set; }

VALIDATION CONTROLLER

//The date parameter here is always null, even when the field contains a correct value to check.

public JsonResult CheckDateNotInPast(DateTime? date)
        {
            return Json((date == null || DateTime.UtcNow.Date <= date.Date), JsonRequestBehavior.AllowGet);
        }

VIEW

<div class="col-sm-5">
            @Html.TextBoxFor(m => m.Deadline, new { @placeholder = (Model.Deadline == null ? "YYYY-MM-DD" : Model.Deadline.Value.ToString("yyyy-MM-dd")), @class = "form-control", @id = "datepicker" })
            <span class="nais-error-text">@Html.ValidationMessageFor(m => m.Deadline)</span>
        </div>
1

1 Answers

1
votes

Your property is named Deadline, therefor the parameter in your controller method must match. Change it to

public JsonResult CheckDateNotInPast(DateTime? deadline)

and it will be correctly passed.

As a side note, you can use a conditional validation attribute (such as a foolproof [GreaterThanOrEqualTo], or you can easily create your own) so that your get client and server side validation without need the extra overhead of an ajax call (which after the initial validation, will be done on every .keyup() event by default).