jquery ui datepicker and mvc view model type datetime
Asked Answered
B

3

10

I am using jquery datepicker on my view model

Here is my view:

@Html.TextBoxFor(o => o.JobStartDate, new { id = "dt1", @class = "input-block-level" })
@Html.ValidationMessage("JobStartDate")

and my script:

$("#dt1").datepicker({ dateFormat: "dd/mm/yy" });

Everything works fine if my date is <= 12, if my date is over 12, it will show me an validation error message saying "The field Start Date must be a date." (I am using jquery validation)

For example: date 16/12/2014 will give me the error while 12/12/2014 won't

Here is my view model:

[Required]
[DataType(DataType.Date)]
[Display(Name = "Start Date")]
public DateTime JobStartDate { get; set; }

I am suspecting that my view model is anticipating a date in the format mm/dd/yyyy while on my datepicker i specified dd/mm/yy, is there a way to tell my viewmodel that I am expecting dd/mm/yy format so that it doesn't throw an error message if date is >= 12.

Belier answered 4/12, 2014 at 2:52 Comment(0)
L
13

You can look at using the jquery globalize or add the following to your script (assuming of course that the server culture date format is 'dd/MM/yyy')

$.validator.addMethod('date', function (value, element) {
  if (this.optional(element)) {
    return true;
  }
  var valid = true;
  try {
    $.datepicker.parseDate('dd/mm/yy', value);
  }
  catch (err) {
    valid = false;
  }
  return valid;
});
$('#dt1').datepicker({ dateFormat: 'dd/mm/yy' });

and please use @Html.ValidationMessageFor(m => m.JobStartDate)

Laidlaw answered 4/12, 2014 at 5:31 Comment(0)
S
0

Here MVC View Model:

    public DateTime? date { get; set; }

This is for script :

    $('.DatePickers').datetimepicker({
        timepicker: false,
        format: 'd-M-Y',
        scrollInput: false,
        closeOnDateSelect: true
    });

keypress event for readonly date picker

    $(".DatePickers").keypress(function (event) { event.preventDefault(); });
Syringe answered 1/12, 2017 at 10:43 Comment(0)
W
-2

You will need to create a custom validator. You need to modify your property to take a string value instead like this

public string JobStartDate {get; set; }

You will then need to create your custom validator like this

public class CheckDateAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
        // Validate your Date here
    }
}

After this you will just decorate your property as such -

[CheckDate]
public string JobStartDate {get; set;}

Here is a good tutorial on custom validators

Wagshul answered 4/12, 2014 at 3:45 Comment(1)
This does not do client side validation (and certainly wont solve OP question) and you should never use string for a date!Laidlaw

© 2022 - 2024 — McMap. All rights reserved.