Formatting time for user input in ASP.Net MVC
I have a form that users are allowed to enter time values in (say, hours spent performing some task). A business requirement is that the time be entered in either hh:mm format, or decimal format. In either case, there could potentially be quite a bit of client side javascript for display "helping"--showing totals, validating against other input, etc.
So, for instance, one user might enter "8:30" for Eight Hours Thirty Minutes, while another might enter "8.5" to mean the same thing. I'm looking for something that would let me keep the form/validation duplication to a minimum.
What are the best ways to go about this with the m开发者_开发问答odel and the view?
The regular expression to allow both formats wouldn't be that complicated. I would perform that simple validation client-side via javascript. Beyond that, you may want to add some business validation (at the business object level) for this.
I used jQuery to create a slider that would change the time in the input box in the right format. In my View File, Create.aspx, put the following jquery function somewhere in the beginning of the body.
<script>
$(function () {
$("#slider").slider({
value: 9,
min: 0,
max: 1440,
step: 15,
slide: function (event, ui) {
var hours = Math.floor(ui.value / 60);
var minutes = ui.value - (hours * 60);
var ampm = "AM";
if (hours == 12) { ampm = "PM"; }
else if (hours == 0) { hours = 12; ampm = "AM"; }
else if (hours > 12) { hours = hours - 12; ampm = "PM"; }
if (hours < 10) hours = '0' + hours;
if (minutes < 10) minutes = '0' + minutes;
$("#work_StartTime").val(hours + ':' + minutes + ' ' + ampm);
}
});
});
</script>
then down in the body of the same page put a div near the textbox for time input. A slider will show up at that div
<div class="editor-field">
<%: Html.EditorFor(model => model.work.StartTime)%>
<div id="slider"></div>
<%: Html.ValidationMessageFor(model => model.work.StartTime)%>
</div>
this will give you a slider. In the above javascript code change the step:15, makes increments to be 15 minutes. This is obviously a client side validation. A server side validation should also be implemented of course.
精彩评论