2

I am trying to create a custom validation method for my date time field, and i follow example at here: Jquery validate date range fails and here: Validate that end date is greater than start date with jQuery

Following is my form ( in mvc 3 razor partial view ):

@using (Html.BeginForm("CreateFood", "Stock", FormMethod.Post, new { id = "formData" }))
{
       @Html.ValidationSummary(false, "Opps. Please correct the mistakes")
       <div class="editor-label">
           Storage Date
       </div>
       <div class="editor-field">
          @Html.EditorFor(model => model.StorageDate, new { @class = "storedate" })
          @Html.ValidationMessageFor(model => model.StorageDate)
       </div>

       <div class="editor-label">
          Expiry Date
       </div>
       <div class="editor-field">
         @Html.EditorFor(model => model.ExpiryDate, new { @class = "expirydate" })
         @Html.ValidationMessageFor(model => model.ExpiryDate)
       </div>
 }

And the script:

jQuery.validator.addMethod("dateRange", function () {
        var date1 = new Date(jQuery(".expirydate").val());
        alert(date1);
        var date2 = new Date(jQuery(".storedate").val());
        alert(date2);
        alert(date1 < date2);
        return (date1 < date2);
    }, "Please check your dates. The start date must be before the end date.");

$createdialog.dialog("option", "buttons", {
        "Cancel": function () {
            $createdialog.dialog('close');
        },
        "Submit": function () {

            // Validate the form before ask for cabinet
            var frm = $('#formData');

            var validator = frm.validate({
                rules: {
                    "ExpiryDate": { dateRange: true }
                }
            });
            if (frm.valid()) {
                 submitForm();
            }

Question:

  1. I am not really sure about the syntax and what should I put at "ExpiryDate" (is it a selector? or is the form field name? ): var validator = frm.validate({ rules: { "ExpiryDate": { dateRange: true } }

  2. All the alert() in the method doesnt show, so I assume the method is never fire.. Any idea??

(PS: I am using datepicker for both date field with specific format as well:

  $('.storedate').datepicker({ dateFormat: 'D, dd M yy' });
  $('.expirydate').datepicker({ dateFormat: 'D, dd M yy' });

)

Really need help here... already been searching methods for few days just to implement the datetime validation...

Appreciate any feedback... Thanks... });

Community
  • 1
  • 1
shennyL
  • 2,764
  • 11
  • 41
  • 65

2 Answers2

0

First of all, I'm going to recommend you the library http://momentjs.com/ to deal with dates and its validations.

In my case the custom rule validation was not being fired because .NET MVC is configurating automatically the form validation. So I had to remove that configuration before applying mine (to be able to use custom Kendo UI methods,...) and then all worked fine.

Here you have the Javascript code sample:

var errorPlaceholder = $("<div></div>");

function initializeFormValidator() {
    jQuery.validator.addMethod("year", function(value, element, options) {
        return (new Date().getFullYear()) >= parseInt(value, 10);
    });

    jQuery.validator.addMethod("greater20", function(value, element, options) {
        return (($(element).data("kendoDropDownList").value() == "1") && (parseFloat($(options).val()) >= 20.0));
    });

    $.data($("#myFormId")[ 0 ], "validator", null); //Remove previous configuration
    $("#myFormId").validate({
        focusInvalid: true,
        ignore: "",
        onkeyup: false,
        onfocusout: false,
        errorElement: "div",
        errorPlacement: function(error, element) {
            error.appendTo(errorPlaceholder);
        }
    });
}

function validateForm() {
        var ok = $("#myFormId").valid();
        if(!ok) {
            Utils.ShowAlert("Invalid form", errorPlaceholder.html(), BootstrapDialog.TYPE_WARNING);
        }

        return ok;
    }

And the markup sample for one input ;)

<input data-msg-year="The construction year must be lower than the current year" data-rule-year="true" id="CARACTERISTICAS_GENERALES_antigue_cons" max="2100" min="1700" name="CARACTERISTICAS_GENERALES.antigue_cons" step="1" type="text" value="1700" data-role="numerictextbox" class="k-input error"/>