简体   繁体   中英

ASP MVC data validation model attributes

I am using data annotation attributes to provide metainfo for client side validation. The following code adds data-val-date attribute correctly to the corresponding html input element:

    [DataType(DataType.Date)]
    public DateTime? TestDate { get; set; }

I have date and time input fields too and I would like to apply different validation rules there. However adding different DataType value changes nothing in the rendered input element:

    [DataType(DataType.DateTime)]
    public DateTime? TestDate { get; set; }

rendered in the very same way I mean it renders also a data-val-date attribute so at client side the two kinds of input validation is indistinguishable.

As a bonus using

    [DataType(DataType.Time)]
    public DateTime? TestDate { get; set; }

renders no data-val attribute. Then what's the use of the different DataType attributes?. And more importantly, how can I correctly render a data-val-datetime and data-val-time attributes? (what I am going to handle in a custom way at client side using jQuery validation)

The purpose of the DataType attributes is, in part, to inform things like Html.EditorFor what template to use. However, if you're simply calling something like @Html.TextBoxFor(m => m.TestDate) in your view, then the DataType begins to have more limited utility.

The client-side validation is a separate library that MVC merely utilizes. As you can see at the documentation for that library , there is no "datetime" validator, only "date" and "dateISO". Also conspicuously missing is "time".

The best thing you could actually do here, though, is to utilize the HTML5 input types, as not only will they validate proper date/time/datetime inputs, but they should automatically localize to the user's preferred format (assuming the browser follows the specs in this regard).

To fully utilize your DataType attribute, you should render your inputs with Html.EditorFor , which will include the proper HTML5 input type by default based on the DataType .

Short of that, you can specify the type manually:

 @Html.TextBoxFor(m => m.TestDate, new { type = "date" })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM