【问题标题】:Validation with Ajax POST使用 Ajax POST 进行验证
【发布时间】:2016-07-06 07:41:32
【问题描述】:

我有一个使用 Ajax 设置为 POST 的表单。目前我的验证基本上是这个功能:

// Function for making all fields required
$(function(){
    $("input").prop('required',true);
});

这很好用,但是由于我的部分表单使用 CSS 隐藏,具体取决于先前选择的答案 - 我在控制台中的所有隐藏字段中都收到以下错误:

An invalid form control with name='providerName' is not focusable.

有没有一种更简单的方法可以向 Ajax 表单添加验证,或许还有更多控制权?

例如某些字段需要链接 - 我想我可以验证输入是否具有“链接结构”

我的 Ajax POST 代码示例:

// Wait for the DOM to be loaded 
$(document).ready(function() {

    // Make sure New Provider is unchecked by default   
    document.getElementById("typeNew").checked = false;

    // Variable to hold request
    var request;

    // Bind function to form submit event
    $("#createPanelForm").submit(function(event){

        // Abort any pending request
        if (request) {
            request.abort();
        }

        // Setup local variable
        var $form = $(this);

        // Select and cache form fields
        var $inputs = $form.find("projectName, projectLink, type, providerName, completeLink, quotaFullLink, screenoutLink, existingProvider");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Disable the inputs for the duration of the Ajax request
        // Disabled form inputs will not be serialized.
        $inputs.prop("disabled", true);

        // Send the request
        request = $.post({
            url: "actions/createpanel.action.php",
            method: "POST",
            data: serializedData,
            function(result){
                alert(result);
            }
        });

        // Callback handler for successful request
        request.done(function (response, textStatus, jqXHR){
            // Log data to console
            console.log(serializedData);
            console.log(response);
            document.getElementById('submitSuccess').style.display = 'block';
        });

        // Callback handler for failed request
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to console
            console.error("Error: "+textStatus, errorThrown);
            document.getElementById('submitError').style.display = 'block';
        });

        // Callback handler for both outcomes
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        // Prevent default form posting
        event.preventDefault();

        // Hide form and show response
        $("#createPanelForm").fadeOut(1000);
        $("#submitResponse").delay(1001).fadeIn(1000);      
    });

})

【问题讨论】:

标签: javascript php jquery ajax validation


【解决方案1】:

向表单添加 novalidate 属性会有所帮助:

<form name="myform" novalidate>

【讨论】:

  • 如果你能发布一些例子或sn-p会更好。或者这也可以是评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 2023-04-05
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多