0

I have an Ajax form in my MVC application that is validated using jquery validation. Initially the validation wasn't working because the date fields where in a UK format instead of US (which is by design as I'm UK based), so I added some code to stop that.

Jquery Validation Date

$(function () {
    $.validator.addMethod("date", function(value, element) {
        var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/;
        return value.match(dateReg);
    }, "Invalid date");

    $('#form').validate({
        submitHandler: function(form) {
            form.submit();
        }
    });
});

The code I added however hijacks the form.submit which means the ajax form doesn't trigger it's success or failure functions.

Ajax Form Code

@using (Ajax.BeginForm("Create", "Fixtures", new AjaxOptions
{
    OnSuccess = "Success",
    OnFailure = "Failure"    
}, new { @class = "standard-form", @Id = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    ...Form fields etc...
}

Script

function Success() {
    console.log("Success")
}
 function Failure() {
    console.log("Failure")
}

The whole way this is doesn't doens't feel clean to me, so my question is how do I validate the form correctly (using jquery validate or an alternative) but also retain the success and failure functions of my ajax form?

Yanayaya
  • 2,044
  • 5
  • 30
  • 67
  • How about using `DataAnnotations` to validate your model or view model and combine that with jQuery unobtusive validation? – umutesen Oct 24 '16 at 09:45
  • Your regex is not validating a date. If you want to allow for a `dd/MM/yyyy` format, then you can look at using [jquery globalize](https://github.com/jquery/globalize) or if your using a jquery datepicker, then use its methods (refer [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) for jQuery-ui datepicker). –  Oct 24 '16 at 09:47
  • Alternatively you could use the script in [this answer](http://stackoverflow.com/questions/30594128/error-in-date-validation-mvc/30609111#30609111) –  Oct 24 '16 at 09:49
  • And note you also need to remove the `$('#form').validate({... });` script - that does not work with `jquery.validate.unobtrusive.jds` –  Oct 24 '16 at 10:00
  • Why don't you set the date format for jQuery to UK format instead? – Haitham Shaddad Oct 25 '16 at 10:41

1 Answers1

0

Thanks, in the end and after a little digging through some of the documentation you guys mentioned I found that you can set dateITA to true. Here is the code for this.

    $("#form").validate({
        rules: {
            dateITA: true
        }
    })

This approach works very well for my application and means I can retain all my Ajax form options without any problems. Since I only ever have one form in my views there was no need to worry about the use of conflicting ids.

Yanayaya
  • 2,044
  • 5
  • 30
  • 67