Inputting Time Values

Apr 11, 2012 at 3:53 AM


I'm not sure whether I've managed to completely overlook how to do this in the reference documentation, so I apologies if this is something that I should have worked out myself.

I need to have fields that accept only the time portion of a DateTime property on and object, but even with the mask attribute set the input is rendered as a date picker. How do I customise these to allow input of a time value of various formats?



Apr 11, 2012 at 9:47 AM
Edited Apr 11, 2012 at 10:59 AM

You could switch the date picker off in the Javascript, but then you wouldn't get it on any date fields, which is probably unsatisfactory.  Or you could write a view for the object(s) that need this Time field.  Also a bit fiddly.

I think what I would be inclined to do here is, where you want time only, is mark the DateTime property as [Hidden] and then create a separate, derived (not persisted), String property, which is shown to, and edited by the user, and which does the validation using RegularExpression and/or a validation method. This is a bit of a fiddle, but much easier to unit test than mucking around with views  (I'm very biassed that way!).

Something like this  (I haven't run this code!):


public DateTime StartTime1 {get; set;}


[NotPersisted, RegularExpression("[to be written]")] //

public string StartTime {

get {

return //StartTime1 to a string, suitably formatted


set {

//parse the input value and set StartTime1 accordingly



public string ValidateStartTime(string time) {

// test parsing in here


Apr 28, 2012 at 2:47 AM

Thankyou for pointing me in the right direction Richard.

I had to shift the parsing of values into the action collecting the time values as I'm using Code First and don't have the ability to use non-persisted entity's. RegEx string makes it quite impossible for an invalid time value to be entered.