Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
Donovan Woodside Avatar asked Feb 07 '11 18:02

Donovan Woodside


2 Answers

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.

like image 80
pavsaund Avatar answered Nov 13 '22 21:11

pavsaund


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

like image 24
Zote Avatar answered Nov 13 '22 20:11

Zote