Donovan Woodside
Donovan Woodside

Reputation: 1911

jQuery Mobile and Unobtrusive Validation

I'm creating a jQuery Mobile (Alpha 3) based ASP.NET MVC 3 application utilizing the unobtrusive validation that comes with MVC3. When a page is accessed directly (no hash in the Url), validation works perfectly. However, when you navigate to the page, jQuery Mobile uses Ajax Navigation to dynamically load it (displaying the hash in the Url) and validation stops working.

Here is a sample of the code in use:

Model:

[Required(ErrorMessage = "Missing value")]
[DisplayName("Property Display Name")]
public int? PropertyName { get; set; }

View (Razor):

@Html.LabelFor(model => model.PropertyName)
@Html.TextBoxFor(model => model.PropertyName)
@Html.ValidationMessageFor(model => model.PropertyName)

Generated HTML:

<label for="PropertyName">Property Display Name</label>
<input data-val="true" data-val-number="The field Property Display Name must be a number." data-val-required="Missing value" id="PropertyName" name="PropertyName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="PropertyName" data-valmsg-replace="true"></span>

It is possible that other pages have been loaded previously and the HTML elements no longer have unique Ids. Other than rolling my own Html Helper class to generate the HTML for the Label, TextBox, and ValidationMessage, is there any way to handle this scenario?

Upvotes: 9

Views: 5280

Answers (3)

Anand
Anand

Reputation: 4551

I solved the same problem I encountered, my answer is posted here -

Hash navigation problem while using jquery mobile with asp.net mvc2

Upvotes: 0

pavsaund
pavsaund

Reputation: 696

I've been struggling a bit with this same issue, but @Zote pointed me in the right direction.

parse() is the way to go, but make sure to pass in a selector ie:

jQuery.validator.unobtrusive.parse("form")

or

jQuery.validator.unobtrusive.parse(document)

The best way of hooking this up is probably through JQMspageshow event. This would then be triggered after each new page transition, like so, You may also prefer to do this before jqm has done it's magic on the page as well by using the pagebeforeshow event

$('div').live('pageshow',function(event){
  jQuery.validator.unobtrusive.parse(".ui-page-active form");
});

By using the .ui-page-active, you narrow your search down to the currently active page.

Upvotes: 14

Zote
Zote

Reputation: 5379

Did you call jQuery.validator.unobtrusive.parse() after loaded new content? Read this post at Brad Wilson's blog.

Upvotes: 5

Related Questions