【问题标题】:how to check if input field is empty on submit [duplicate]如何检查提交时输入字段是否为空[重复]
【发布时间】:2013-10-28 05:05:19
【问题描述】:

我正在使用 jQuery,所以我想知道只有在输入字段为空时单击提交按钮后如何显示错误消息。

下面的代码我的简单表格如何应用到它。

<form id="myid" name="myid" method="post" action="hook.php">

name : <input type="text" name="name" id="name">

age : <input type="text" name="age" id="age">

<input type="submit" id="submit" name="submit" value="Save" />

</form>

我想显示这样的错误

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以使用 event.preventDefault 来阻止默认操作的发生。然后检查您的条件,如果条件失败则显示错误,否则提交表单。

    $("#submit").click(function(event) {
      event.preventDefault();
      if($(this).val().length === 0) {
        // display some error  
      } else {
        $("#myid").submit();
      }
    });
    

    【讨论】:

      【解决方案2】:

      您可以在输入标签中使用 HTML5 required='required' 选项...

      【讨论】:

        【解决方案3】:

        正如有人已经提到的,您可能应该考虑使用外部库进行验证。也就是说,这似乎可以工作(see JSFiddle)

        var $form = $("#myid"),
            $errorMsg = $("<span class='error'>This field is required..!!</span>");
        
        $("#submit").on("click", function () {
            // If any field is blank, we don't submit the form
            var toReturn = true;
            $("input", $form).each(function () {
                // If our field is blank
                if ($(this).val() == "") {
                    // Add an error message
                    if (!$(this).data("error")) {
                        $(this).data("error", $errorMsg.clone().insertAfter($(this)));
                    }
                    toReturn = false;
                }
                // If the field is not blank
                else {
                    // Remove the error message 
                    if ($(this).data("error")) {
                        $(this).data("error").remove();
                        $(this).removeData("error");
                    }
                }
            });
            return toReturn;
        });
        

        【讨论】:

        • 这完全完美~非常感谢
        【解决方案4】:

        真的,我建议您使用一些框架进行表单验证。因为这是常见的任务,并且之前已经完成了 100000 次。它有很多,例如ParsleyJquery plugin,但还有很多其他的简单且易于维护,只需 google 'javascript form validation'

        在这种情况下,为什么已经实现的代码比自定义代码更好:1)它已经编写、测试和工作,2)您几乎不需要只需要一次验证,并且真正为多个参数验证表单可能是一个挑战,并且可能导致大量的验证代码 3) 框架是 DRYer 和很多其他的东西。

        【讨论】:

          【解决方案5】:

          我还建议您使用验证框架,因为您需要针对不同领域进行更多验证。使用 MooTools Floor 这是最可靠的验证框架。 MooTool Floor

          【讨论】:

            猜你喜欢
            • 2011-08-18
            • 1970-01-01
            • 1970-01-01
            • 2018-04-18
            • 2019-03-28
            • 2012-04-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多