I’ve written before about the peculiarities of ASP.NET MVC validation. It’s a great technology 90% of the time, but can cause issues if you do something a little out of the ordinary. I came across another one of these unusual circumstances recently when I was testing my development version of CocktailsRUs.
I was running through the site checking that upgrading to the latest version of jQuery Mobile hadn’t broken anything when I noticed something interesting – on one page, the validation ran but nothing visual happened to show that it had done so. The validation worked – the page did not submit – but there was nothing to tell the user what had happened.
It turned out there were two issues. One was a twist on the ASP.NET MVC validation issues I mentioned in that earlier post. The other was specific to jQuery Mobile.
Here is a screenshot of the jQuery Mobile page AFTER the validation has run. As you can see – it is not very helpful:
So I took a look at the same functionality in the normal Web view, and the result is a little different – but still not what it is supposed to be:
So I had two problems, not one: the highlighting wasn’t working in the mobile version, and the message wasn’t working in either. Time to do a little digging….
Here is the code inside the .cshtml page:
The element and the validation attributes have been hard-coded to get around ASP.NET MVC’s problems with validation and repeating forms. Those problems stem from the fact that ASP.NET MVC uses IDs instead of name attributes to hook up validation. This time, however, the problem is that when it comes to displaying the result of the validation, it DOES use name attributes – and you’ll notice that in the code sample above, the ”name” does not match the (case-sensitive) ”Name” model property in the ValidationMessageFor() method.
So I changed the name attribute value to match the model property…
And now we have a validation message:
But it’s still not quite right – unlike the Web view, where both highlighting and text are visible:
So what’s going on with the search element in jQuery Mobile? We have a working label, but the input itself doesn’t have the usual CSS look and feel to highlight the error. In this case, the problem lies in the way that jQuery Mobile creates the search box.
It turns out that that the ”search” input is being converted to a text input, given a wrapping div and (unsurprisingly) all sorts of CSS decoration.
The upshot is that the standard MVC CSS validation classes can’t compete and are overridden.
So how to fix it? By tweaking the CSS to make the ASP.NET MVC CSS classes more powerful. In this case, I am only using the search type with a very small number of IDs – so I added CSS rules specific to those IDS…
And the problem went away:
So – back to coding… until the next interesting little niggle comes along.
For other related information, check out these courses from Learning Tree: