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

时间:2020-12-31 20:17:32

I want to validate the input field 'putime' in the form because even if the 'putime' input box is empty the result is calculated and nightSurcharges is also added to the cost. So I want to validate 'putime' when it is empty otherwise the script is useless.

我想在表单中验证输入字段'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>

I've tried a lot but to no avail....any help is welcomed. Thanks in advance!

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

1 个解决方案

#1


2  

how about adding an event handler to the form, in the likes of document.forms[0].submit = validateFunction;

如何在文档中添加事件处理程序,如document.forms [0] .submit = validateFunction;

where validateFunction might look like this:

其中validateFunction可能如下所示:

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

#1


2  

how about adding an event handler to the form, in the likes of document.forms[0].submit = validateFunction;

如何在文档中添加事件处理程序,如document.forms [0] .submit = validateFunction;

where validateFunction might look like this:

其中validateFunction可能如下所示:

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