Is it possible to validate a form that has been loaded dynamically by Ajax? I have two forms that I load on a page with another form and niether of the Ajax forms can be validated.
Does anyone know a workaround?
Thank you,
Irv Lennert
ajaxajax frameworks in mvcasp.net MVC Validationajax asp.net mvcvalidationn MVCasp .net mvc 3ASP .NET mvc 3 razor
Is it possible to validate a form that has been loaded dynamically by Ajax? I have two forms that I load on a page with another form and niether of the Ajax forms can be validated.
Does anyone know a workaround?
Thank you,
Irv Lennert
Irv,
It is not a workaround. Whenever you load new unobtrusive validation attributes, they must be parsed in order to create your validation logic. Add the following script as part of each Ajax form:
<script type="text/javascript">
$(document).ready(function() {
$("[INSERT THE ID OF YOUR AJAX FORM HERE]").each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
});
</script>
Once the Ajax form is parsed, you will have your validation.
If that script that you suggested was part of what I am dynamically loading how would anything every see it or know it was there?
I think I need some sort of .live() call from the form that it loads in.
Irv,
I realized that my answer was incomplete. You can either insert the following script at the bottom of each partial you are loading:
<script type="text/javascript">
$(document).ready($(function () {
$jQval.unobtrusive.parse("#vendorAddressForm"); // or "#vendorContactForm" for your other partial
});
</script>
or you can insert it as a function on your main page, and pass the id of the partial back to your function using a script in each partial.
All you need to do is to parse the unobtrusive validation included as "data-val-" attributes in the html loaded by your partials, and you will have your validation.
ajax loaded partial views will not run inline javascript. you need to trigger the validation parse from the main page, after the load via OnComplete in the ajaxoptions
I have tryed everything on this thead and nothing seems to work. I have found however, that inline javascript does work on the partial view. I have also noted that the function call thru the Ajax OnComplete gets fired as well. It just doesn't seem to
enable the unobtrusive js to work , in other words, I get no validation on the Ajax loaded form I'm having no trouble on any other part of the view (the static loaded part). I am still noware with this.
ajax loaded partial views will not run inline javascript. you need to trigger the validation parse from the main page, after the load via OnComplete in the ajaxoptions
Bruce,
I just wrote a simple example, using the following code:
public class First
{
[Required(ErrorMessage = "First name required")]
[DisplayName("First Name")]
public string FirstName { get; set; }
}
public class Last
{
[Required(ErrorMessage = "Last name required")]
[DisplayName("Last Name")]
public string LastName { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(new First());
}
public ActionResult Last()
{
return PartialView(new Last());
}
This works as expected. Click the "Show Last Name Box" button, and the Last Name box appears, the script from the Last partial is executed, and the Last Name box's Required unobtrusive validation attributes are parsed, and the "Last name requried" message
will appear.
One last note: I missed that "$jQval" is a local name, and the correct call is to "$.validator"
counsellorben
Marked as answer by ilennert on Feb 11, 2011 09:42 PM
I want to add further information to anyone that finds this thread helpful. Most of the problem I was having had to do with the fact that I had change to jQuery 1.5. I was changing a few things at once and thought that it was the selector change that fixed
the problem but if I switch back to jQuery 1.5 the unobtrusive parsing ether stops or something else about 1.5 is not compatable.
I want to add further information to anyone that finds this thread helpful. Most of the problem I was having had to do with the fact that I had change to jQuery 1.5. I was changing a few things at once and thought that it was the selector change that fixed
the problem but if I switch back to jQuery 1.5 the unobtrusive parsing ether stops or something else about 1.5 is not compatable.
Hope this helps someone.....
Irv
Irv,
I updated my test project to use jquery-1.5, and it worked as expected. I don't believe that jquery-1.5 introduces any breaking changes into MVC's unobtrusive validation.
ilennert
Member
29 Points
20 Posts
Unobtrusive validation not working on form loaded by Ajax
Feb 10, 2011 09:40 PM|LINK
Is it possible to validate a form that has been loaded dynamically by Ajax? I have two forms that I load on a page with another form and niether of the Ajax forms can be validated.
Does anyone know a workaround?
Thank you,
Irv Lennert
ajax ajax frameworks in mvc asp.net MVC Validation ajax asp.net mvc validationn MVC asp .net mvc 3 ASP .NET mvc 3 razor
counsellorbe...
Member
540 Points
112 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 10, 2011 11:09 PM|LINK
Irv,
It is not a workaround. Whenever you load new unobtrusive validation attributes, they must be parsed in order to create your validation logic. Add the following script as part of each Ajax form:
<script type="text/javascript"> $(document).ready(function() { $("[INSERT THE ID OF YOUR AJAX FORM HERE]").each(function () { var info = validationInfo(this); if (info) { info.attachValidation(); } }); }); </script>Once the Ajax form is parsed, you will have your validation.
counsellorben
ilennert
Member
29 Points
20 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 11, 2011 12:11 AM|LINK
counsellorben,
If that script that you suggested was part of what I am dynamically loading how would anything every see it or know it was there?
I think I need some sort of .live() call from the form that it loads in. Here so you get the full picture:
The main view:
@model JandJ.Model.VendorViewModel @{ ViewBag.Title = "Vendor Create Edit"; } <h2>Vendor Create Edit</h2> @using (Ajax.BeginForm("VendorCEAjax", new AjaxOptions { UpdateTargetId = "editZone" })) { @Html.ValidationSummary(true) <fieldset id="vendorInfo"> <legend>Vendor Info</legend> @Html.Hidden("ids", "") @Html.HiddenFor(m => m.VendorId) <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div id="vendorExt"> <div id="addresses" style="float: left; width: 40%;"> <table> <tr> <th></th> <th> Address </th> </tr> @foreach (var item in Model.VendorAddresses) { <tr> <td> <a id="@string.Format("Address_{0}", item.VendorAddressId)" class="processSubmit" href="#">Edit</a> </td> <td> @item.Address.Line1 @if (item.Address.Line2 != null) { <br/>@item.Address.Line2 } @if (item.Address.Line3 != null) { <br/>@item.Address.Line3 } <br />@item.Address.City<span>, </span>@item.Address.State<span> </span>@item.Address.PostalCode @if (item.Address.Country != null && item.Address.Country != "US") { <br />@item.Address.Country } </td> </tr> } </table> <a id="Address_0" class="processSubmit" href="#">Add Address</a> </div> <div id="contacts" style="float: left; width: 60%;"> <table> <tr> <th></th> <th> Contact Info </th> </tr> @foreach (var item in Model.VendorContacts) { <tr> <td> <a id="@string.Format("Contact_{0}", item.VedorContactId)" class="processSubmit" href="#">Edit</a> </td> <td> <span>@item.ContactLabel: @item.ContactType | @item.ContactInfo</span> </td> </tr> } </table> <a id="Contact_0" class="processSubmit" href="#">Add Contact</a> </div> </div> <input id="vendorSubmit" type="submit" value="Post" style="display: none;"/> </fieldset> } <div id="editZone"> </div> <div> @Html.ActionLink("Back to Vendors List", "Vendors") </div> <script type="text/javascript"> $(document).ready(function () { $(".processSubmit").click(function () { $("#ids").val($(this).attr("id")); $("#vendorSubmit").submit(); return false; }); $("#ContactInfo").live('focusout', function () { return runRegex(patFromValue($("#ContactTypeId").val())); }); $("#vendorContactForm").live('submit', function (event) { var retVal = runRegex(patFromValue($("#ContactTypeId").val())); if (retVal == false) event.preventDefault(); return retVal; }); //$(".processSubmit").button(); }); function patFromValue(selVal) { var patEmail = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$"; var patPhone = "^\\(?[\\d]{3}\\)?[\\s-]?[\\d]{3}[\\s-]?[\\d]{4}$"; if (selVal == '1') { return patEmail; } else if (selVal == '2') { return patPhone; } else return ""; } function runRegex(rgex) { var re = new RegExp(rgex); if ($("#ContactInfo").val().match(re)) { return true; } else { alert("Contact Info is not valid for that Contact Type."); return false; } } </script>Then when some one clicks on one of the Edit links I load Get VendorAddress or GetVendorContact forms that loaded as PartialView(s)
@model JandJ.Model.VendorAddressViewModel <div id="vendorAddress"> @using (Html.BeginForm("GetVendorAddress", "Admin", FormMethod.Post, new { id = "vendorAddressForm" })) { @Html.ValidationSummary(true) <fieldset> <legend>Vendor Address</legend> @Html.HiddenFor(m => m.VendorAddressId) @Html.HiddenFor(m => m.AddressVendorId) <div class="editor-label"> @Html.LabelFor(model => model.AddressLabel) </div> <div class="editor-field"> @Html.EditorFor(model => model.AddressLabel) @Html.ValidationMessageFor(model => model.AddressLabel) </div> <div class="editor-label"> @Html.LabelFor(model => model.CorpAddressTypeId) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CorpAddressTypeId, Model.CorpAddressTypes) @Html.ValidationMessageFor(model => model.CorpAddressTypeId) </div> @Html.EditorFor(m => m.Address) <div class="vendorCmp"> <input type="submit" value="Save" /> </div> </fieldset> } </div>@model JandJ.Model.VendorContactViewModel <div id="vendorContact"> @using (Html.BeginForm("GetVendorContact", "Admin", FormMethod.Post, new { id = "vendorContactForm" })) { @Html.ValidationSummary(true) <fieldset> <legend>Vendor Contact</legend> @Html.HiddenFor(m => m.VedorContactId) @Html.HiddenFor(m => m.ContactVendorId) <div class="editor-label"> @Html.LabelFor(model => model.ContactLabel) </div> <div class="editor-field"> @Html.EditorFor(model => model.ContactLabel) @Html.ValidationMessageFor(model => model.ContactLabel) </div> <div class="editor-label"> @Html.LabelFor(model => model.ContactTypeId) </div> <div class="editor-field"> @Html.DropDownListFor(m => m.ContactTypeId, Model.ContactTypes) @Html.ValidationMessageFor(model => model.ContactTypeId) </div> <div class="editor-label"> @Html.LabelFor(model => model.ContactInfo) </div> <div class="editor-field"> @Html.EditorFor(model => model.ContactInfo) @Html.ValidationMessageFor(model => model.ContactInfo) </div> <div class="vendorCmp"> <input id="vcSubmit" type="submit" value="Save" /> </div> </fieldset> } </div>counsellorbe...
Member
540 Points
112 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 11, 2011 02:47 AM|LINK
Irv,
I realized that my answer was incomplete. You can either insert the following script at the bottom of each partial you are loading:
<script type="text/javascript"> $(document).ready($(function () { $jQval.unobtrusive.parse("#vendorAddressForm"); // or "#vendorContactForm" for your other partial }); </script>or you can insert it as a function on your main page, and pass the id of the partial back to your function using a script in each partial.
All you need to do is to parse the unobtrusive validation included as "data-val-" attributes in the html loaded by your partials, and you will have your validation.
counsellorben
bruce (sqlwo...
All-Star
36644 Points
5432 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 11, 2011 05:12 AM|LINK
ajax loaded partial views will not run inline javascript. you need to trigger the validation parse from the main page, after the load via OnComplete in the ajaxoptions
ilennert
Member
29 Points
20 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 11, 2011 05:06 PM|LINK
I have tryed everything on this thead and nothing seems to work. I have found however, that inline javascript does work on the partial view. I have also noted that the function call thru the Ajax OnComplete gets fired as well. It just doesn't seem to enable the unobtrusive js to work , in other words, I get no validation on the Ajax loaded form I'm having no trouble on any other part of the view (the static loaded part). I am still noware with this.
If anone has a clue I'd love to here it.
Thanks for your time,
Irv
counsellorbe...
Member
540 Points
112 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 11, 2011 05:40 PM|LINK
Bruce,
I just wrote a simple example, using the following code:
public class First { [Required(ErrorMessage = "First name required")] [DisplayName("First Name")] public string FirstName { get; set; } } public class Last { [Required(ErrorMessage = "Last name required")] [DisplayName("Last Name")] public string LastName { get; set; } } public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(new First()); } public ActionResult Last() { return PartialView(new Last()); }Here is the Index view:
@model TestApp.Controllers.First @{ ViewBag.Title = "Home Page"; } <h2>@ViewBag.Message</h2> <div> @using (Html.BeginForm()) { <div> @Html.LabelFor(m => m.FirstName)<br /> @Html.TextBoxFor(m => m.FirstName) @Html.ValidationMessageFor(m => m.FirstName) </div> } @using (Ajax.BeginForm("Last", new AjaxOptions() { UpdateTargetId = "lastDiv" })) { <div> <input type="submit" value="Show Last Name Box" /> </div> } <div id="lastDiv"></div> </div>Here is the partial view called by Ajax:
@model TextApp.Controllers.Last @using (Html.BeginForm()) { @Html.LabelFor(m => m.LastName)<br /> @Html.TextBoxFor(m => m.LastName) @Html.ValidationMessageFor(m => m.LastName) <script type="text/javascript"> $(document).ready(function() { $.validator.unobtrusive.parse("#lastDiv > form"); }); </script> }This works as expected. Click the "Show Last Name Box" button, and the Last Name box appears, the script from the Last partial is executed, and the Last Name box's Required unobtrusive validation attributes are parsed, and the "Last name requried" message will appear.
One last note: I missed that "$jQval" is a local name, and the correct call is to "$.validator"
counsellorben
ilennert
Member
29 Points
20 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 11, 2011 09:56 PM|LINK
Hey counsellorben,
I got it to work. I just had to change it a little. I think the problem it that I put my PartialView inside and other div. So I just changed it to:
<script type="text/javascript"> $(document).ready(function() { $.validator.unobtrusive.parse("#editZone > div > form"); });If you look at my PartialViews above you'll see why.
Thanks for all your help!
Irv
ilennert
Member
29 Points
20 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 13, 2011 06:04 PM|LINK
I want to add further information to anyone that finds this thread helpful. Most of the problem I was having had to do with the fact that I had change to jQuery 1.5. I was changing a few things at once and thought that it was the selector change that fixed the problem but if I switch back to jQuery 1.5 the unobtrusive parsing ether stops or something else about 1.5 is not compatable.
Hope this helps someone.....
Irv
counsellorbe...
Member
540 Points
112 Posts
Re: Unobtrusive validation not working on form loaded by Ajax
Feb 13, 2011 11:20 PM|LINK
Irv,
I updated my test project to use jquery-1.5, and it worked as expected. I don't believe that jquery-1.5 introduces any breaking changes into MVC's unobtrusive validation.
counsellorben