JavaScript - 验证用户输入

时间:2015-06-11 16:57:16

标签: javascript html

我有一个网页应该接收用户的联系信息并对其进行验证,但我的脚本似乎无法正常运行,我不确定原因。

我知道您可以使用我所拥有的document.getElementById(name).value来获取文本字段的输入,但我的submit按钮不响应任何内容。

有什么建议吗?

HTML:

<form>
    First Name:<br>
        <input type="text" id="first" name="firstname"><br>
    Last Name:<br>
        <input type="text" id="last" name="lastname"><br>
    Street Address:<br>
        <input type="text" id="addr" name="address"><br>
    City:<br>
        <input type="text" id="city" name="city"><br>
    State:<br>
        <input type="text" id="state" name="state"><br>
    Zip Code:<br>
        <input type="text" id="zip" name="zip"><br>
    Phone #:<br>
        <input type="text" id="phone" name="phone"><br>
    E-mail Address:<br>
        <input type="text" id="email" name="email"><br>
    <br>
    <button type="button" onclick="verify()">Submit</button>
</form>

JavaScript的:

function verify() {
    var fname, lname, addr, city, state, zip, phone, email;
    var alpha = /[A-z]/i;

    fname = document.getElementById('first').value;
    lname = document.getElementById('last').value;
    addr = documnet.getElementById('addr').value;
    city = document.getElementById('city').value;
    state = document.getElementById('state').value;
    zip = document.getElementById('zip').value;
    phone = document.getElementById('phone').value;
    email = document.getElementById('email').value;

    var values = [fname, lname, addr, city, state, zip, phone, email];

    window.alert(fname);

    /*
    //Check to see if any fields are blank
    for(var i = 0; i < values.length; i++) {
        if(values[i] == "") {
            window.alert("Must have a value in each field");
            return false;
        }
    }

    //Check to see if text fields contain non-alphabetic characters
    if(!alpha.test(fname)) {
        window.alert("First name must contain only alphabetic characters");
        return false;
    }
    if(!alpha.test(lname)) {
        window.alert("Last name must contain only alphabetic characters");
        return false;
    }
    if(!alpha.test(city)) {
        window.alert("City must contain only alphabetic characters");
        return false;
    }
    if(!alpha.test(state)) {
        window.alert("State must contain only alphabetic characters");
        return false;
    }
    */
}

1 个答案:

答案 0 :(得分:1)

你输错了

daemontools

应该是

addr = documnet.getElementById('addr').value;

注意文档

的拼写

除此之外,您的代码似乎工作正常。请参阅fiddle