Unobtrusive Validation and KnockoutJS form submit

posted in: Uncategorized | 0

I’ve been playing with some MVC4, Knockout JS and some unobtrusive validation, specifically I was trying to replicate the Grid Editor Example.

 

I had a problem with the example when I had:

$("form").validate({ submitHandler: function () {
    viewModel.save();
} });

 

It would still call the viewModel.save(), which would in term post my data back to the server even if I had errors. This worked “ok” in most cases as my model validation picked up most things, but if for example I’d put a string in a number field, that’s when everything came to a screaming halt.

After a bit of poking around I found that changing the previous statement for this one made everything happy again:

$.validator.setDefaults({ submitHandler: function() {
             viewModel.save();
        } });