Daveo
Daveo

Reputation: 19872

ASP.Net MVC 3 client side validation with a dynamic form

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;
});

Upvotes: 13

Views: 12854

Answers (3)

Daveo
Daveo

Reputation: 19872

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

Upvotes: 16

Abdul Qadir Memon
Abdul Qadir Memon

Reputation: 1019

The best solution is to call $.validator.unobtrusive.parse('#frmToBeValidated'), right after your ajax load of dynamic form.

Upvotes: 10

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

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!

Upvotes: 8

Related Questions