0

我有一些用javascript编写的代码,可以根据一组允许的数字验证字段中输入的数字。我遇到的问题是,即使我输入了正确的数字,它也会返回false。这是我的代码:

window.onload=function() {

var validNumbers = {
 "2474": 2474,
 "2750": 2750,
 "2753": 2753,
 "2760": 2760,
 "2777": 2777
};
function validate(num) {
return typeof validNumbers[num] !== "undefined";
};

var button = document.getElementById("submit"),
userInput = document.getElementById("post");
button.onclick = function(event) {
alert("Please enter a correct postcode");
};
}

<form name="eoiform" form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">

<input type="text" id="post" name="post"><?php echo $msgp; ?></td>

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

</form>

谁能提供一些关于我的错误的见解?或者可能有更好的方法来写出来?

4

2 回答 2

2

看起来很复杂?只需将输入的值解析为整数,并根据数组进行检查,如果数组中存在该值,则提交表单,如果没有警告消息并返回 false。

您应该验证提交事件,因为除了单击按钮之外还有其他方法可以提交表单(例如在输入框中按回车键)。

将脚本放在 HTML 之后,同时去掉那个 window.onload :

<form name="eoiform" form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
    <input type="text" id="post" name="post"><?php echo $msgp; ?></td>
    <input type="submit" name="submit" id="submit" value="submit">
</form>
<script>
    var form         = document.getElementById('eoi'),
        validNumbers = [2474,
                        2750,
                        2753,
                        2760,
                        2777
                       ];

    form.onsubmit = function() {
        var userInput = document.getElementById("post"),
            numb      = parseInt(userInput.value, 10);

        if ( validNumbers.indexOf(numb) == -1 ) {
            alert("Please enter a correct postcode");
            return false;
        }else{
            return true;
        }
    }
</script>

小提琴

于 2013-05-23T08:17:17.153 回答
1

那这个呢?考虑到您的验证功能永远不会被调用。

var validNumbers = {
    "2474": 2474,
    "2750": 2750,
    "2753": 2753,
    "2760": 2760,
    "2777": 2777
};

function validate(num) {
    return typeof validNumbers[num] !== "undefined";
};

var button = document.getElementById("submit"),
    userInput = document.getElementById("post");

button.onclick = function(event) {
    var val = validate(userInput.value)
    if(!val) {
        alert("Please enter a correct postcode");
        return false;
    } else {
        alert("Thanks");
        // Run your code here
        // Form will submit
    }
};

http://jsfiddle.net/n7SxE/

于 2013-05-23T08:17:18.267 回答