1

Have problem with fancybox and jquery validate plugin when form is in fancybox container.

For examle (inline): html:

<script>
$(document).ready(function(){  $.fancybox('
<form class="myform">
<input type="text" name="email" class="email" />

<input type="submit" value="submit" name="submit" />
</form>
');
})
</script>

js file:

$(".myform").validate(
          {
          rules: {
            email: "required",
            email: "email"
                 }
           }
        );

How to make jquery validation pluging to work in fancybox?

5
  • You must invoke .validate() after the form is created.
    – Sparky
    Commented Jun 4, 2013 at 16:34
  • you could initialize the validation plugin inside the fancybox's beforeShow callback
    – JFK
    Commented Jun 4, 2013 at 17:09
  • @JFK, I don't think beforeShow will work. The form must be constructed before .validate() is called. afterLoad is more appropriate.
    – Sparky
    Commented Jun 4, 2013 at 19:19
  • @Sparky : beforeShow works pretty much fine to me jsfiddle.net/ZMEEW/1
    – JFK
    Commented Jun 4, 2013 at 20:08
  • @JFK, indeed it does.
    – Sparky
    Commented Jun 4, 2013 at 22:24

1 Answer 1

4

Do two things...

  1. Use the afterLoad FancyBox callback function to initialize .validate() immediately after the form is loaded.

  2. Put the content for FancyBox in a hidden div instead of in your jQuery. It's cleaner.

Note: You may want to reconsider using email for the name attribute. It has potential to cause great confusion since the rule is also called email.

HTML:

<a id="test" href="#inline">Test</a>

<div style="display:none" id="inline">
    <form class="myform">
        <input type="text" name="email" class="email" />
        <input type="submit" value="submit" name="submit" />
    </form>
</div>

jQuery:

$(document).ready(function () {

    $('#test').fancybox({
        afterLoad: function() {
            $('.myform').validate({
                // rules and options for validate plugin,
                rules: {
                    email: {  // "email" is name of the field
                        required: true,
                        email: true // "email" is name of the rule
                    }
                }
            });
        }
    });

});

Working DEMO: http://jsfiddle.net/ZMEEW/

2
  • you could always use beforeShow because the form is already constructed, not visible yet though
    – JFK
    Commented Jun 4, 2013 at 20:16
  • @JFK, ok, use either one. Whatever.
    – Sparky
    Commented Jun 4, 2013 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.