8

how can I avoid the generation of the html attribute "data-val-date" for the element created from a Datetime property?

The model:

public class RegisterModel
{
    [Required]
    [Display(Name = "Date of birth")]
    public DateTime? DateOfBirth { get; set; }
}

The view:

@Html.LabelFor(m => m.DateOfBirth)
@Html.EditorFor(m => m.DateOfBirth)

In fact, I'm creating a three drop down lists element for selecting the date of birth, which don't give a value in a date format. Some solutions I've seen, consisted in a work around: removing the validation with a javascript. The solution I envisage is to split the DateTime property into three long one for each value (day, month, year).

bado
  • 83
  • 1
  • 3

3 Answers3

16

Ok, this took me an afternoon of work... apparently mvc4 decided that it was time to render a data-val-date="Message" on EVERY datetime property on the viewmodel. I've tried to modify this default behaviour but didn't succeed.

This solved my problems:

$.validator.addMethod('date',
    function (value, element) {
        return true; // since MVC4 data-val-date is put on EVERY vm date property. Default implementation does not allow for multiple cultures...
    });

You can also try to write your own editor template named "DateTime.cshtml" in your shared EditorFor folder, but don't use TextBoxFor there, because that one is polluted as well.

Ciprian Teiosanu
  • 1,553
  • 16
  • 19
nicojs
  • 1,879
  • 2
  • 18
  • 34
  • I prefer this solution because it only disables the cause of the problem. Client side validation provides a better user experience and reduces post-backs to your server, so disabling the whole thing should be avoided. – Tony Wall Feb 08 '13 at 10:37
  • still useful +1ed – user2695433 Sep 21 '17 at 08:10
0

data-val-date is used by the validation system to validate the date. If you remove it, client-side validation won't work.

If that's what you want, then just disable client-side validation.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Okay thanks for your quick answer. Disabling the client-side validation will have effect on every elements? In my side, I opt for a new object containing my three values and replacing the datetime. – bado Sep 26 '12 at 18:09
  • @bado - i'm sorry, I don't understand what you mean. – Erik Funkenbusch Sep 26 '12 at 18:11
  • I have to precise, I just begin in web technos. I meant if I disable client-side validation, all the data-val (of all elements on the form) will have no effect? – bado Sep 26 '12 at 18:16
  • @bado - if you turn off client-side validation then it will no longer generate any of the data-val attributes. – Erik Funkenbusch Sep 26 '12 at 18:25
0

Add this to your application start in your global.asax file and the form should fire.

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
vikingben
  • 1,632
  • 2
  • 24
  • 37