首页 > 解决方案 > 如何使用 JavaScript 对文本输入执行验证检查?

问题描述

对于我的作业,我需要做的一件事是创建一个表格来填写信用卡详细信息并对其进行验证检查。为简单起见,我将验证数字(信用卡号和 CVV)是否为整数以及它们是否在特定范围内(以检查已输入的位数。所以 CVV 不应该小于 100 不大于 999)。

编辑:这是我的 html 代码:

<form name="payment" action="thankyou.php" onsubmit="validation();" method="POST">
<--inputs here-->
<button type="submit" class="btn">Continue to checkout</button>
</form>
validation(){
var num=document.getElementByID("ccnum"); //num and ccnum are the credit card numbers
var safenum=document.getElementByID("cvv"); //cvv and safenum are the safety numbers

if (!(Number.isInteger(num)) || (num>9999999999999999) || (num<1000000000000000)){
     window.alert("Invalid credit card number.")
} //detect whether the credit card number is an integer, larger than 9999999999999999, smaller than 1000000000000000 or not
else if (!(Number.isInteger(safenum)) || (safenum>1000) || (safenum<100)){
     window.alert("Invalid credit card safety number.")
} //detect whether the safety number is an integer, larger than 999, smaller than 100 or not
else {
    window.open("thankyou.php")
} //the inputs are valid and the user is sent to another web page

当我单击submit运行的表单按钮时function(),它只是重新加载页面,而不是显示任何警报消息或重定向到thankyou.php。知道如何重写我的代码吗?

标签: javascript

解决方案


这是因为您使用表单标签。当您按提交或按 ENTER 时将提交您的表格。只需将此代码插入表单标记中。

如果您的 HTML 是这种格式,

<form action="thankyou.php" method="POST" 
         onsubmit="event.preventDefault(); validation();" id="myForm">
        <button type="submit" class="btn">Continue to checkout</button>
    </form>

然后将此行添加到您的表单标签。

 <form action="thankyou.php" method="POST" onsubmit="event.preventDefault(); validation();" id="myForm">

并将您的验证功能更改为此。

function validation(){
    var num=document.getElementByID("ccnum"); //num and ccnum are the 
    credit card numbers
var safenum=document.getElementByID("cvv"); //cvv and safenum are the 
    safety numbers

    if (!(Number.isInteger(num)) || (num>9999999999999999) || (num<1000000000000000)){
         window.alert("Invalid credit card number.")
    } //detect whether the credit card number is an integer, larger than 9999999999999999, smaller than 1000000000000000 or not
    else if (!(Number.isInteger(safenum)) || (safenum>1000) || (safenum<100)){
         window.alert("Invalid credit card safety number.")
    } //detect whether the safety number is an integer, larger than 999, smaller than 100 or not
    else {
        myForm.submit();

    }
    }

推荐阅读