【问题标题】:jquery validation doesn't work for ajax loaded bootstrap modal dialog contentjquery 验证不适用于 ajax 加载的引导模式对话框内容
【发布时间】:2014-04-21 00:45:51
【问题描述】:

我正在使用带有 zend 2 的引导程序。 modal 的内容是通过 ajax 调用来获取的。 但是验证根本不起作用,它在不检查任何字段的情况下提交:

这里是模态加载的地方:

<div class="modal fade" id="themesModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

        </div>
    </div>
</div>

这里是模态内容:

<div class="modal-body">
    <div id="themesbox">
        <div class="panel panel-info">

            <div class="panel-heading">
                <div class="panel-title">title</div>
            </div>

            <div style="padding-top: 30px" class="panel-body">
                           <?php
                                $form = $this->form;
                                $form->setAttribute('action', $this->url('user/default', array('controller' => 'users', 'action' => 'create')));
                                $form->prepare();
                                echo $this->form()->openTag($form);
                                ?>

                                <div id="mydiv"
                    style="display: none" class="alert alert-danger">
                    <p>Error:</p>
                    <span></span>
                </div>


                <div class="form-group">
                    <label for="name" class="col-md-3 control-label">user</label>
                    <div class="col-md-9">
                                        <?php echo $this->formElement($form->get('name'));?>
                                    </div>
                </div>

                <div class="form-group">
                    <label for="description" class="col-md-3 control-label">password</label>
                    <div class="col-md-9">

                                        <?php echo $this->formElement($form->get('password'));?>
                                    </div>
                </div>


                <div style="margin-top: 10px" class="form-group">
                    <!-- Button -->
                    <div class="col-sm-12 controls">
                    <?php echo $this->formSubmit($form->get('submit'));?>
                    <button id="cancel" class="btn btn-success" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
                    <?php echo $this->form()->closeTag();?>  
            </div>
            <!-- /.panel-body -->
        </div>
        <!-- /. panel panel-info -->
    </div>
</div>

这里是jquery验证代码:

 $('.form-validation').each(function () {
     $(this).validate({


    errorElement: "span",
    errorClass: "help-block",   

    highlight: function(element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
        $(element).attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
    },
    unhighlight: function(element) {
        $(element).addClass('valid').closest('.control-group').removeClass('error').addClass('success');
        $(element).attr('style', "border-radius: 4px; border:1px solid #ccc;");
    },
    errorPlacement: function (error, element) {
        $(error).attr('style', "color: #FF0000;");
        if ( element.prop('type') === 'checkbox') {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }

  });
 });

这是表单代码:

 $this->add(array(
            'name' => 'name',

            'attributes' => array(
                'type'  => 'text',
                'id' => 'username',
                'class'  => 'form-control',
                'required'  => 'true',
                'minlength'  => '8',
                'maxlength'  => '20',
            ),
            'options' => array(
                'label' => 'name',
            ),
        ));

        $this->add(array(
            'name' => 'description',

            'attributes' => array(
                'type'  => 'password',
                'id' => 'password',
                'class'  => 'form-control',
                'required'  => 'true',
                'minlength'  => '8',
                'maxlength'  => '20',
            ),
            'options' => array(
                'label' => 'Password',
            ),
        ));

【问题讨论】:

  • 不显示 Zend 代码,而是显示浏览器看到的相关 HTML 标记。
  • @Sparky 我可以将包含上述 js 代码的 js 脚本包含在 html 中
  • 显示相关的 HTML “证明”该标记适用于 JavaScript。我们还应该如何确定您的 jQuery Validate 脚本不工作的原因?
  • @Sparky 请看我的回答

标签: zend-framework2 jquery-validate twitter-bootstrap-3 bootstrap-modal


【解决方案1】:

我使用不同的方法进行这项工作。

与其尝试在客户端进行自己的验证(添加错误 HTML 等),不如通过 AJAX 提交表单并让 ZF2 返回带有表单标记的 JsonModel

如果您使用正确的视图助手(特别是FormRow),它将正确呈现表单错误。

例如

class FooController extends AbstractActionController
{

   public function createAction()
   {
     $request = $this->getRequest();
     $service = $this->getServiceLocator()->get('FooService'); 
     $form    = $service->getFooCreateForm(); // Zend\Form

     if ($request->isPost()) {
        $form->setData($request->getPost());

        if ($form->isValid()) {

            $foo = $service->create($form->getData());

            if ($foo instanceof Foo)
                // redirect to success page
            } else {
                $this->flashMessenger()->addErrorMessage('Error!');
            }
            return $this->redirect()->toRoute('foo', array('action' => 'index'));

        } else if ($request->isXmlHttpRequest()) {

            $renderer = $this->getServiceLocator()->get('viewrenderer');
            $formView = new ViewModel(compact('form')); // add the form to the view
            $formView->setTemplate('foo-module/foo/form');

            return new JsonModel(array(
                'success' => false, // Flag to keep modal open
                'content' => $renderer->render($formView), // The "content" being the form HTML
                'message' => 'Please check all form fields have been completed successfully',
            ));
        }
     }
     return new ViewModel(compact('form'));
   }

}

form.phtml

<?php
  echo $this->form($this->form);

create.phtml

//...modal html
<div class="modal-body">
    <?php echo $this->partial('form.phtml', compact('form')); ?>
</div>
//... modal html

你还想:

  • 从 ZF2 表单中删除所有按钮(因为模式已经有两个)
  • 在模态提交按钮和AJAX发布表单内容中添加一个JS事件监听器 到createAction
  • 如果调用结果为success == true则关闭模态
  • 如果结果是success == false,您将拥有content 变量,然后可以使用$('.modal-content').html(result.content) 替换现有的模式内容,这将包括经过验证的表单HTML(包括生成的所有错误查看表单视图助手)。

【讨论】:

  • 虽然总是进行服务器端验证是个好主意,但在这种情况下,OP 会询问客户端验证。通常两者都使用;客户端以提供更好的用户体验和服务器端以防前者失败。
  • @Sparky 您所说的“更好的体验”是为了避免页面刷新,对吧?这种方法通过 AJAX 提交表单并使用表单视图助手构建 HTML;没有页面重新加载;您需要做的就是将表单内容替换为来自 AJAX 调用的响应。在我看来,这比复制可能复杂的验证服务器端(您必须通过 javascript 添加 HTML 内容)要好。这将很难维护和扩展 - 例如,如果您要向表单添加一个字段。
  • 我的主要观点是您的解决方案并未专门解决 OP 的问题。
【解决方案2】:

事实上,所有的服务器端验证机制都已经到位并且运行良好。

我需要通过 jquery 进行客户端验证。

由于Bootstrap模态对话框的内容是从ajax加载的,所以没有像往常一样考虑周围的上下文,我需要插入jquery ajax 内容中的代码。

ZF2 不允许在其视图文件中插入 js 代码。

所以我按照以下方式在 ajax 内容中插入以下行:

 <?php echo $this->inlineScript()->appendFile($this->basePath() . '/js/custom.js')?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多