13

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;
});
Daveo
  • 19,018
  • 10
  • 48
  • 71

3 Answers3

15

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

Daveo
  • 19,018
  • 10
  • 48
  • 71
  • 1
    hint: you need to specify a selector: e.g. parse('body') – ulrichb Aug 28 '13 at 07:40
  • Agree with @ulrichb. Without a selector (or a jQuery object) it didn't work for me. BTW: bigger scope will mean worst performance, so instead of `'body'` you should send `$("#MyForm")` or whatever element you loaded dynamically – Diego May 28 '15 at 20:22
9

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

Abdul Qadir Memon
  • 950
  • 1
  • 12
  • 27
8

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!

Yngve B-Nilsen
  • 9,606
  • 2
  • 36
  • 50
  • thanks that is an excellent answer and I did learn alot from it. However after some digging around I realised my issue only occurs when the form is loaded on the fly and I have updated/changed my question significantly at the same time you answered. sorry. But I think your email will help many ppl all the same – Daveo Mar 11 '11 at 13:10
  • aha :) I'm pretty sure this then has to do with how the validator-javascript hooks up events. Since the elements are not there on page load, but are added to the DOM later, it might not register the events correctly (not using .live() for instance). I must say I've never used the .validate() method, so not really sure what that does. – Yngve B-Nilsen Mar 11 '11 at 13:32