【问题标题】:jQuery dialog validation using jquery.validate()使用 jquery.validate() 进行 jQuery 对话框验证
【发布时间】:2017-08-29 16:21:23
【问题描述】:

当我点击提交按钮时,它仍然提交表单而不验证字段。我也在这里查看了其他解决方案,但没有问题提到在提交时单击功能中要做什么。

这是我的代码:https://jsfiddle.net/ishtiaq156/an1xqoxz/

表格

      $('#submitContact').click(function() {
        var customerId = $('#customerId').val();
        var formData = $('#addCustomerForm').serialize();

        $.ajax({
          url: "/abc/admin/customer/" + customerId + "/addContact",
          type: "POST",
          dataType: "json",

          data: formData,
          success: function(data) {
            location.reload();
          },
          failure: function(errMsg) {
            alert(errMsg);
          }

        });
      });

JavaScript:

 $('#submitContact').click(function() {
                var customerId = $('#customerId').val();
                var formData = $('#addCustomerForm').serialize();

                $.ajax({
                  url: "/abc/admin/customer/" + customerId + "/addContact",
                  type: "POST",
                  dataType: "json",

                  data: formData,
                  success: function(data) {
                    location.reload();
                  },
                  failure: function(errMsg) {
                    alert(errMsg);
                  }

                });
              });

【问题讨论】:

    标签: jquery forms validation jquery-ui-dialog


    【解决方案1】:

    我过去做过的一种方法是将提交处理程序添加到调用您的 ajax 函数的验证代码中。然后您可以将按钮更改为 type="submit"

    $('#addCustomerForm').validate({
        rules: {
            /* removed for brevity */
        },
        messages: {
            /* removed for brevity */
        },
        submitHandler: function (form) {
            updateRecord();
            /* $("#dialog-form").dialog("close"); -  if using dialog */
        }
        /* ....add other options as needed */
    });
    
    function updateRecord() {
        var customerId = $('#customerId').val();
        var formData = $('#addCustomerForm').serialize();
    
        $.ajax({
            url: "/abc/admin/customer/" + customerId + "/addContact",
            type: "POST",
            dataType: "json",
    
            data: formData,
            success: function(data) {
               location.reload();
            },
            failure: function(errMsg) {
               alert(errMsg);
            }
        });
    } 
    

    此外,您可以使用数据发送所有表单变量,而不是在 URL 中添加一些变量:

    data: {
        customerId: customerId,
        addContact: "addContact",
        ...add other form fields 
    }
    

    【讨论】:

    • 完美。我需要这两件事:submitHandler 和作为提交的输入类型。现在可以使用了。
    【解决方案2】:

    你应该在这里发布控制台日志

    确保您已包含 jquery 验证插件

    or download it

    【讨论】:

    • 是的。我确实添加了 jquery.validate.js,我可以通过在 Chrome 开发工具中单击 ctrl+p 来验证它是否已加载。此外,没有要发布的控制台错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多