Recently, I spent a fair bit of time recently trying to figure out why in our latest ASP.NET MVC projects jquery client side validation just doesn’t want to work properly. Well it appears that there are different issues. The good news though is they can be fixed.

I spent a fair bit of time recently trying to figure out why in our latest ASP.NET MVC projects jquery client side validation just doesn’t want to work properly. Well it appears that there are different issues. The good news though are that they can be fixed.

jquery.validate.unobtrusive.js problems

ASP.NET MVC unobtrusive jquery validation just doesn’t work. Full stop. It actually stopped working since the jquery release 1.9.0 (current version at the moment of writing is 1.10.2). There was a breaking change in that release in the way $.parseJSON works – it now doesn’t forgive invalid JSON format and throws an exception. After some debugging efforts I found the culprit – jquery.validate.unobtrusive.js. Even the latest (v.3) version of it contains 2 similar blocks of code where the value parsed is not properly JSON formatted:


replace = $.parseJSON(container.attr('data-valmsg-replace')) !== false;

where

container.attr('data-valmsg-replace')

is a string ‘true’.

There are 2 quick solutions to the problem:

  • Use a jquery version prior 1.9.0. I found that 1.8.3 is perfectly fine as it allows the wrong jquery.validate.unobtrusive.js JSON format.
  • Don’t use a CDN version of jquery.validate.unobtrusive.js (as it was in my case), get a local copy and patch it. A quick patch would be something like:

var replace = true;
if (container.attr('data-valmsg-replace') != 'true') {
  try {
    replace = $.parseJSON(container.attr('data-valmsg-replace')) !== false;
  } catch (e) {
  }
}

Date validation problems in Chrome

Chrome browser (and reportedly Safari) ignores browser culture settings and always treats dates in the US format – unfortunate in our situation as we need “dd/MM/yyyy”. Therefore date field validation in Chrome always fails on date fields when days are 13-31.

The solution is to substitute jquery.validate.js’s own ‘date’ validation method with a custom one which does exactly what we want:


$.validator.methods['date'] = function (value, element) {
  var check = false;
  var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
  if (re.test(value)) {
  var adata = value.split('/');
  var dd = parseInt(adata[0], 10);
  var mm = parseInt(adata[1], 10);
  var yyyy = parseInt(adata[2], 10);
  var xdata = new Date(yyyy, mm - 1, dd);
  if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
    check = true;
  else
    check = false;
  } else
  check = false;
  return this.optional(element) || check;
}

Enjoy your client side validation!

ASP.NET MVC jquery validation

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.