【问题标题】:Stop form submission on input element validation在输入元素验证时停止表单提交
【发布时间】:2012-06-21 19:44:30
【问题描述】:

我不怎么用 Javascript。

我想做的是有一个表单,用户可以在其中输入他们的邮政编码,以查看他们是否在选定数量的邮政编码(客户的服务区域)内。

如果他们的邮政编码在列表中,我想将他们发送到一个 URL 以安排约会。如果它不在列表中,我想要某种警报,上面写着“抱歉,您的邮政编码不在我们的服务区域内”。

我有一些适应这种工作的东西,但无论用户输入什么,都会将用户发送到页面。

非常感谢任何帮助!

<form name = "myform" action="http://www.google.com/">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5" onchange = "checkZip()">
<button id="submit">Submit</button>
</form>

<script type = "text/javascript">
    function checkZip() {

        var z = document.myform.zip;
        var zv = z.value;
        if (!/^\d{5}$/.test(zv)) {
            alert("Please enter a valid Zip Code");
            document.myform.zip.value = "";
            myfield = z; // note myfield must be a global variable
            setTimeout('myfield.focus(); myfield.select();', 10); // to fix bug in
                                                                  // Firefox
            return false;
        }

        var codes = [ 12345, 12346, 12347, 12348, 12349, 12350 ]; // add as many
                                                                  // zip codes as
                                                                  // you like,
                                                                  // separated by
                                                                  // commas (no
                                                                  // comma at the
                                                                  // end)
        var found = false;
        for ( var i = 0; i < codes.length; i++) {
            if (zv == codes[i]) {
                found = true;
                break;
            }
        }

        if (!found) {
            alert("Sorry, the Zip Code " + zv + " is not covered by our business");
            document.myform.zip.value = "";
            return false;
        } else {
            alert("Press okay to go forward to schedule an appointment");
        }
    }
</script>

【问题讨论】:

  • 有什么问题?你的代码对我有用。输入 12345,我会收到“Press OK....”警报。输入 98765,我会收到“抱歉,邮政编码...”提示。

标签: javascript validation zip


【解决方案1】:

非提交按钮(简单)解决方案

<form name = "myform" action="http://www.google.com/">
    Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
    <button type="button" onclick="checkZip();" id="submit">Submit</button>
</form>

注意:type="button" 的按钮是一个按钮,不会提交w3c

并将checkZip()的最后一个块更改为:

if (!found) {
    alert("Sorry, the Zip Code " + zv + " is not covered by our business");
    document.myform.zip.value = "";
    //do nothing
} else {
    alert("Press okay to go forward to schedule an appointment");
    document.myform.submit();
}

我所做的更改如下:

  • 将 onclick 属性从输入元素移动到提交按钮
  • 将提交按钮更改为“按钮”类型,使其成为按钮。按钮不会自动提交当前表单。

注意:这不会停止在输入元素内按 enter 提交表单的情况。根据下一个解决方案,您将需要一个 onSubmit="" 处理程序来处理该用例。

提交按钮(简单)解决方案

<form name = "myform" action="http://www.google.com/" onsubmit="checkZip()">
    Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
    <button onclick="checkZip();" id="submit">Submit</button>
</form>

注意:没有类型的按钮默认是提交按钮w3c

并将checkZip()的最后一个块更改为:

if (!found) {
    alert("Sorry, the Zip Code " + zv + " is not covered by our business");
    return false;
} else {
    alert("Press okay to go forward to schedule an appointment");
    return true;
}

我所做的更改如下:

  • checkZip() 调用移至表单上的onsubmit 属性
  • 更改checkZip() 以返回真/假

关于改变解决方案

此解决方案与您的解决方案最接近。然而,它增加了更多的复杂性:

形式:

<form name = "myform" action="http://www.google.com/" onsubmit="onFormSubmit();">
    Enter Your Zip Code
    <input type = "text" id="zipCode" name = "zip" size = "5" maxlength = "5" onchange = "onZipChange()">
    <button id="submit">Submit</button>
    <div id="invalidZipMsg" style="display:none;">
            Sorry, but we do not service your area.
    </div>
</form>

JavaScript:

/**
 * Returns true if we receive a valid zip code.
 * False otherwise.
 * 
 * @param zipCode The zip code to check
 * @returns True/fase if valid/invalid
 */
function isValidZip(zipCode){
    var validZipCodes = {'12345':true, 
                         '12346':true, 
                         '12347':true, 
                         '12348':true, 
                         '12349':true, 
                         '12350':true
                        };

    //can do other checks here if you wish
    if(zipCode in validZipCodes){
        return true;
    } else {
        return false;
    };
}

/**
 * Run on invalid zip code.
 * Disables form submission button and shows
 * error message.
 */
function invalidZipCode(){
    var invalidZipMsg = document.getElementById('invalidZipMsg');
    invalidZipMsg.style.display = "block";

    var submitButton = document.getElementById('submit');
    submitButton.disabled = 'true';
}

/**
 * Run on valid zip code. Enables form
 * submission button and hides the error message.
 * @returns
 */
function validZipCode(){
    var invalidZipMsg = document.getElementById('invalidZipMsg');
    invalidZipMsg.style.display = "none";

    var submitButton = document.getElementById('submit');
    submitButton.disabled = 'true';
}

/**
 * onChange handlers for the zip code input element.
 * Will validate the input value and then disable/enable
 * the submit button as well as show an error message.
 * @returns
 */
function onZipChange(){
    var zipCode = document.getElementById('zipCode');
    if(isValidZipCode(zipCode.value)){
        validZipCode();
    } else{
        invalidZipCode();
    };
}

/**
 * Run on form submission. Further behavior is the same
 * as @see onZipChange. Will stop form submission on invalid
 * zip code.
 */
function onFormSubmit(){
    var zipCode = document.getElementById('zipCode');

    if(isValidZipCode(zipCode.value)){
        validZipCode();
        return true;
    } else{
        invalidZipCode();
        return false;
    };
}

备注

有很多方法可以解决这个问题。我只选择了两个最简单的,一个我觉得可以提供更好的用户体验。当您有不提交但提供不需要表单提交的其他操作的按钮时,非提交解决方案是一个很好的例子。在我看来,最后一个具有最佳的用户体验,但这只是一种意见。

离题

如果您有时间,我建议您查看许多可用的优秀 JavaScript 库。它们通过有意义的简单解决方案帮助引入复杂/高级问题,并且很可能跨浏览器兼容。我按照我的偏好顺序推荐它们:

但请注意,他们需要时间来理解。我知道在处理一个不是首要任务的项目时。

一般来说,开始使用 jQuery 和 JavaScript 的最快方法是:First Flight。无论如何,我与 codeschool.com 没有关联,也没有从他们那里获得任何利润。这个示例是免费的,它是我的团队在工作中为刚开始使用 jQuery 的人们传递的示例。

【讨论】:

  • 安德鲁,非常感谢您的通俗易懂和透彻的回答。他们非常有帮助。我决定使用您的第一个解决方案。它似乎按我想要的方式工作。我在link 上使用它,但它似乎没有正确验证。我输入了一些不在 var 代码中的邮政编码,但它仍在推动它们通过而没有发出警报。但是非常感谢。你帮了很多忙。我确实想学习 jQuery 和 JavaScript。我已经开始接受 Lynda.com 的一些培训,这应该可以让我继续前进。
  • 啊,我明白了。如果我按 Enter 提交,它会自动将我带到 URL。如果我点击“提交”按钮,它将正确验证。虽然如果它是列表中的邮政编码并且弹出警报,它不会将其推送到 URL。
  • onChange 仅在元素失去焦点后触发。如果表单提交发生在焦点丢失之前,则不会触发 onChange。处理这种情况的解决方案是将 onSubmit="" 交给一个处理程序,该处理程序验证邮政编码并返回 true/false 以允许/停止提交。
  • 好的。我已经到了可以通过警报正确验证它是否是列表中的邮政编码的地步。如果它是正确的,它会在警报后向前移动到链接。但如果它不正确,它仍然会在警报之后继续链接。如果在警报后输入了无效的 zip,我不确定如何让它停止。再次感谢您的所有帮助。
【解决方案2】:

我假设您的问题是即使邮政编码无效,用户仍然可以提交表单。

我建议像这样将检查移到表单提交事件中

<form name = "myform" action="http://www.google.com/" onsubmit = "checkZip()">
  Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
  <button id="submit">Submit</button> 
</form>

然后你可以在检查失败时返回 false 取消提交到 google.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 2022-01-06
    • 2016-02-07
    相关资源
    最近更新 更多