I am trying to do manual validation so I can post my form via AJAX.
ALSO I am loading my form dynamically using $("#formHolder").load(url);
When I load the page into the DIV it always validates as true, even though my input box is empty.
i.e call if($("#MyForm").valid()) //is always true
However If I go to the page URL directly it works ok.
So how can I initialise the Form correctly after loading it via .load(url);
since it does not exist on the page when first opened
My Javascript is
$('.myLink').click(function () {
var url = '/newsletter/info/'; // this loads my HTML form from another page/view at runtime
$("#formHolder").load(url, function () {
$("#MyForm").validate(); // I thought this line would initialise it once it loads
}).dialog({
modal: true,
width:800,
height: 600
});
return false;
});
Calling $.validator.unobtrusive.parse()
manually after the form has been loaded works
I found the solution here http://btburnett.com/2011/01/mvc-3-unobtrusive-ajax-improvements.html
The best solution is to call $.validator.unobtrusive.parse('#frmToBeValidated')
, right after your ajax load of dynamic form.
Your question does not specify if you need to do anything custom to validate the form, so I would definitely go with MVC3's built in jquery unobtrusive validation:
If this is your model:
public class Person
{
[Required(ErrorMessage = "Email address required")]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter valid email address")]
public string Email { get; set; }
}
this Form-code in your view will enable validation instantly with a minimum amount of settings:
@model MvcApplication12.Models.Person
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Ajax.BeginForm(new AjaxOptions())) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
If you want more functionality when the form is posted you can use AjaxOptions:
new AjaxOptions() { UpdateTargetId = "formupdate",
OnSuccess = "javascript:alert('success');",
OnFailure = "javascript:alert('failure');",
OnComplete = "javascript:alert('complete');",
OnBegin = "javascript:alert('begin');" })
This gives you full control over custom actions as the form is submitted, completed, fails or begins.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With