如何在用户输入无效时包含javascript错误消息

时间:2016-01-31 17:06:12

标签: javascript

当我输入值时,我成功地为年龄提供了输出,但是我需要验证发出错误的输入并向浏览器粘贴警告消息。我正在使用if语句,但它不起作用。

 <!DOCTYPE html>
    <html>
        <body>
            <form>
                Birth Year:
                <br>
                <input type="text" name="birthYear">
                <br>
                Current Year:
                <br>
                <input type="text" name="currentYear">
            </form>
            <button onclick="calculateAge()">Calculate Age</button>
            <div id="output"></div>



<script>
    function calculateAge() {
    var ghF = document.querySelector('[name="birthYear"]').value;
    var xhF = document.querySelector('[name="currentYear"]').value;
    document.getElementById("output").innerHTML = "You are either "+(xhF - ghF)+" or "+(xhF - ghF + 1)

    if (ghF) || (xhF) !== "number" {
        confirm("Invalid, please try again")
    }
    };
    </script>

1 个答案:

答案 0 :(得分:0)

您可以使用parseInt方法将用户输入解析为数字:

var ghF = parseInt(document.querySelector('[name="birthYear"]').value, 10);
var xhF = parseInt(document.querySelector('[name="currentYear"]').value, 10);

然后检查NaN:

if (isNaN(ghF) || isNaN(xhF)) {
    // One of the two user inputs couldn't be parsed to a number
    alert('Invalid, please try again');
}

并在实际使用这些值之前进行此检查,例如将其放在条件的else部分:

document.getElementById("output").innerHTML = "You are either " + (xhF - ghF) + " or " + (xhF - ghF + 1);