javascript - 如何使用 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。知道如何重写我的代码吗?
解决方案
这是因为您使用表单标签。当您按提交或按 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();
}
}
推荐阅读
- qt - TextField“拒绝”信号?
- django - JWT Token过期时间增加
- javascript - Angular 中的 [class]="'success'" 和 class="success" 有区别吗?
- android - 如何设置 rtl=false ,仅用于图层?
- r - 将列表对象列表转换为R中的数据框
- haskell - 数据类型的别名
- css - 使用宽度计算Angular 6动态设置CSS属性左侧
- raku - 使用 NativeCall 将 CStruct 中的内联 CArray 传递给共享库
- facebook - Google Chrome / Safari 打开时,相同的 URL 显示两个不同的图像?
- jquery - 使用 jQuery Touch Events (Ben Major) 捕获滑动事件