验证码问题?

时间:2013-05-23 08:07:12

标签: javascript function validation

我有一些用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>

任何人都能对我的错误提供一些见解吗?或者可能是一个更好的方法来写出来?

2 个答案:

答案 0 :(得分: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>

FIDDLE

答案 1 :(得分: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/