ASP.NET MVC3: Validating Date Times and Custom Validation messages

  1. How would I prevent users typing into a datetimepicker (text field), but allow them to use the datetimepicker.
  2. How can I validate that one date is AFTER another, and display it inline (and prevent submitted) exactly like ASP.Net MVC3 does. The javascript isnt so much the problem of checking its after the other, its how I go about displaying this inline message and prevent submitting, Tieing it in with the other validation.

so far I have

            $("#Save").click(function (e) {
                if (  $('#EndTime').val() < $('#StartTime').val() )
                    alert("AHRR"); // Should add an inline message and NOT submit.
            });

Answers


I would suggest using jQuery's datepicker to do date-range constraining on the client side. You would need to disable the input elements <input readonly/>. I've implemented a date range constraint recently that works for me. It constrains an end-date to be within 90 days of the start-date

FYI, I stopped using startElement and endElement as a test, never went back as this code isn't currently reused.

// ============================================================================
// FUNCTION: InitializeDates(startElement, endElement)
// PARAMETERS
// ----------
// startElement:    The element which will be initialized as the start-date 
//                  datepicker.
//
// endElement:      The element which will be initialized as the start-date 
//                  datepicker.
//
// DESCRIPTION
// -----------
// InitializeDates updates the start and end dates for non-employees.  It 
// creates a date-picker object on both fields and then constrains the end 
// end date:
// * No date selections available prior to the start date
// * No date selections available after 90 days beyond the start date.
// ----------------------------------------------------------------------------
function InitializeDates(startElement, endElement)
{
    $("#f-start-date").datepicker({
        showOn: "button",
        buttonImage: "images/calendar.png",
        buttonImageOnly: true,
        onSelect: function(dateText, inst) { StartDateSelected(dateText, inst) }
    });

    $("#f-end-date").datepicker({
        showOn: "button",
        buttonImage: "images/calendar.png",
        buttonImageOnly: true,
        numberOfMonths: 3
    });

    $("#f-start-date").val('');
    $("#f-end-date").val('');
}

// ============================================================================
// FUNCTION: StartDateSelected(dateText, endElement)
// PARAMETERS
// ----------
// dateText:    The dateText passed from jQuery.datepicker.onSelect
// inst:        The instpassed from jQuery.datepicker.onSelect//
//
// DESCRIPTION
// -----------
// Updates the end-date maxDate and minDate fields to 91 dates from the selected
// start date.
// ---------------------------------------------------------------------------
function StartDateSelected(dateText, inst)
{
    var second = 1000;
    var minute =second * 60;
    var hour = minute * 60;
    var day = hour * 24;

    // The datepicker updates maxDate and minDate based on today's date.  I've
    // got to math out dates so that the maxDate is actually 91 days from the
    // selected date.  
    var todaysDate = new Date();
    var selectedDate = new Date(dateText);          
    var duration = Math.floor((selectedDate - todaysDate) / day) + 91;

    $("#f-end-date").datepicker("option", "minDate", selectedDate);
    $("#f-end-date").datepicker("option", "maxDate", duration);
    $("#f-end-date").val('');
}

As far as preventing typing into the datetimepicker fields, use jQuery to hook into the keyup event, and clear any text from the field. Assuming you are using jquery 1.6 or earlier, the code would look like the following:

$("input[id$='Time']").live("keyup", function() {
    $(this).val("");
});

In addition, you might consider adding a placeholder attribute directing the user not to type in the date.

As far as a compare date validator, you will find a good example in this question: MVC3 custom validation: compare two dates


Need Your Help

$sce.TrustAsUrl not Working

javascript html regex angularjs ngsanitize

I am trying to create an app using angularjs where the input is taken from the input box and is displayed. It is similar to a chat. So the input can contain urls and I am converting them to links w...

Difference between if exists (select 1 from) and (select 0 from)

sql sql-server sql-server-2008

Is there any difference at all select 1 from and select 0 from or select any integer from?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.