javascript - 在提交表单之前验证输入字段

标签 javascript validation

我想验证表单中的输入字段“putime”,因为即使“putime”输入框为空,也会计算结果并将 nightSurcharges 添加到成本中。所以我想在'putime'为空时验证它,否则脚本是无用的。

function TaxiFare() {
// calculates taxi fare based upon miles travelled
// and the hour of the day in military time (0-23).

var baseFare = 14;
var costPerMile = 7.00;
var nightSurcharge = 20.50; // 9pm to 6am, every night //its flat 20.50 and not per mile

var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert ("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}

var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime < 0) || (pickupTime > 23) || (pickupTime==null)) {  // note the hours are 0-23.  There is no 24 hour, midnight is 0 hours
alert ("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}

var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 21 || pickupTime < 6) {
cost += nightSurcharge;
}
document.getElementById("result").innerHTML = "Your taxi fare is: $. "  + cost.toFixed(2);
}


And here is the Form from HTML


    <form>
Miles for Journey <input type="text" id = "miles" required><br>
Pickup Time <input type = text id = "putime" required><br><br>
<input type="button" value="Calculate Fare" onclick="TaxiFare()">
<input type="reset" value="Clear"><br><br>
<span id = "result"></span>
</form>

我已经尝试了很多但都无济于事....欢迎任何帮助。提前致谢!

最佳答案

如何向表单添加事件处理程序,例如 document.forms[0].submit = validateFunction;

其中 validateFunction 可能如下所示:

function validateFunction()
{
    var allIns = this.getElementsByTagName('input');
    if(allIns.namedItem('putime').value == '')
    {
        alert('silly');
        return false;
    }
    //and other checks go here, too
}

关于javascript - 在提交表单之前验证输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10143895/

相关文章:

php - 使用 PHP 和 MySQL 验证之间的日期

java - Appengine - 隐藏文件夹的部署

javascript - Google Script 从文件夹中的每个工作表复制到基于文件夹的主工作表?

javascript - 布局上的脚本可以传播到 View 吗?

Javascript 访问私有(private)数组

java - 如果验证失败,如何在验证阶段之后 checkin ?

c++ - 简化 if else 用户输入验证

javascript - 编写自定义验证规则

javascript - 在 Mac 的 Firefox 中旋转后 Div 的边框不是一条直线

javascript - Node JS 同步数据库调用