如何使用 Javascript 验证信用卡到期日?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27054951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:39:32  来源:igfitidea点击:

How do I validate a credit card expiry date with Javascript?

javascripthtmlformsvalidation

提问by Sridhar DD

I'm a complete Javascript beginner and I'm really stuck on my assignment. I have to get the user to enter credit card details and validate them with Javascript. Here are my problems.

我是一个完整的 Javascript 初学者,我真的被我的任务困住了。我必须让用户输入信用卡详细信息并使用 Javascript 验证它们。这是我的问题。

  1. The payment type returns false when you don't select anything (which is what I want it to do), but I've used similar code for the expiry month and year, and those two can return true even if you don't make a selection, I want them to return false.

  2. The expiry date validation I don't really know how to do. It has to only accept dates after today's date. I've sort of come up with something that should work in theory, but doesn't. Is there something simple (remember I'm a beginner!) that I can add or change that would make it work?

  3. There's an issue with the script for the credit card number validation (needs to be 16 numbers) as well, but inexplicably it just doesn't seem to work.

  1. 当您不选择任何内容时,付款类型返回 false(这是我想要它做的),但我使用了类似的到期月份和年份代码,即使您不选择,这两个也可以返回 true一个选择,我希望他们返回 false。

  2. 到期日期验证我真的不知道该怎么做。它必须只接受今天日期之后的日期。我已经想出了一些理论上应该有效的东西,但没有。是否有一些简单的东西(请记住我是初学者!)我可以添加或更改使其工作?

  3. 信用卡号验证脚本(需要 16 个数字)也存在问题,但莫名其妙地似乎不起作用。

My Javascript and html are below.

我的 Javascript 和 html 如下。

Thanks for your help!

谢谢你的帮助!

Best regards,

此致,

Greg

格雷格

JAVASCRIPT

爪哇脚本

function validateForm()
{
var firstName=document.getElementById("firstName");
var lastName=document.getElementById("lastName");
var email=document.getElementById("email");
var postcode=document.getElementById("postcode");
var paymentType=document.getElementById("paymentType");
var exMonth=document.getElementById("exMonth").value;
var exYear=document.getElementById("exYear").value;
var cardNumber=document.getElementById("cardNumber").value;
var date = new Date ();
var month = date.getMonth();
var year = date.getFullYear();

            if (firstName.value===""){
                        alert("Please enter your first name");
                        firstName.focus();
                        return false;
            }
            if (lastName.value===""){
                        alert("Please enter your last name");
                        lastName.focus();
                        return false;
            }
            if (email.value.indexOf(".") == -1 || email.value.indexOf("@")== -1) {
                        alert("Please include a valid email address");
                        email.focus();
                        return false;
            }
        if (postcode.value.length!=4  || isNaN(postcode.value)){
                        alert("Please enter 4 numbers for your postcode");
                        postcode.focus();
                        return false;
            }
        if (paymentType.selectedIndex === 0){
            alert("Please select payment type");
            return false;
        }
        if (exMonth.selectedIndex === 0){
            alert("Please select the month");
            return false;
        }
        if (exYear.selectedIndex === 0){
            alert("Please select the year");
            return false;
        }
        if (year> exYear || (year === exYear && month >= exMonth)){
            alert("The expiry date is before today's date. Please select a valid expiry date");
            return false;
        }
        if (cardNumber.value.length!=16  || isNaN(cardNumber.value)){
                        alert("Please enter 16 numbers for your credit card");
                        cardNumber.focus();
                        return false;
            }
            alert("Thank you for your submission");
            return true;
}

HTML

HTML

<form name="myForm" autocomplete="on" onsubmit="return validateForm()">

<p><label>First name &#40;required&#41; <input type="text" id="firstName" 
autofocus="autofocus" /> </label></p> 

<p><label>Last name &#40;required&#41; <input type="text" id="lastName"/> </label></p>

<p> Email address &#40;required&#41;
<input type="text" id="email" /> </p> 

<p> Postcode &#40;required&#41;
<input type="text" id="postcode"/> </p> 

<p> Payment type &#40;required&#41;
<select id="paymentType" title="Choose a payment type">
  <option value="0">Select a payment option</option>
  <option value="visa">VISA</option>
  <option value="master">Mastercard</option>
  <option value="amer">American Express</option>
</select>
</p>

<p> Expiry date &#40;required&#41;
<select id="exMonth" title="select a month">
<option value="0">Enter month</option>
    <option value="01">January</option>
    <option value="02">February</option>
    <option value="03">March</option>
    <option value="04">April</option>
    <option value="05">May</option>
    <option value="06">June</option>
    <option value="07">July</option>
    <option value="08">August</option>
    <option value="09">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>

<select id="exYear" title="select a year">
 <option value="0">Enter year</option>
    <option value="2013">2013</option>
    <option value="2014">2014</option>
    <option value="2015">2015</option>
    <option value="2016">2016</option>
    <option value="2017">2017</option>
    <option value="2018">2018</option>
    <option value="2019">2019</option>
    <option value="2020">2020</option>
    <option value="2021">2021</option>
    <option value="2022">2022</option>
    <option value="2023">2023</option>
    <option value="2024">2024</option>
    <option value="2025">2025</option>
    <option value="2026">2026</option>
    <option value="2027">2027</option>
    <option value="2028">2028</option>
    <option value="2029">2029</option>
    <option value="2030">2030</option>
    <option value="2031">2031</option>
</select>
</p>
<p><label>Credit card number &#40;required&#41; <input type="text" id="cardNumber"/> </label></p> 
<div id="centreimg">
<input type="submit" name="S1" value="Submit response" />
<input type="reset" name="reset" value="Clear form" /> 
</div>
</form> 

回答by Sridhar DD

And for the credit card expiration validation you can do like this.

对于信用卡到期验证,您可以这样做。

var today, someday;
var exMonth=document.getElementById("exMonth");
var exYear=document.getElementById("exYear");
today = new Date();
someday = new Date();
someday.setFullYear(exYear, exMonth, 1);

if (someday < today) {
   alert("The expiry date is before today's date. Please select a valid expiry date");
   return false;
}

回答by Rama Kathare

In the following code you have some deviations

在以下代码中,您有一些偏差

var firstName=document.getElementById("firstName");
var lastName=document.getElementById("lastName");
var email=document.getElementById("email");
var postcode=document.getElementById("postcode");
var paymentType=document.getElementById("paymentType");
//here why did you use .value. Probably removing .value would fix your issue
var exMonth=document.getElementById("exMonth").value;
var exYear=document.getElementById("exYear").value;
var cardNumber=document.getElementById("cardNumber").value;

change the last three lines to something like this

把最后三行改成这样

var exMonth=document.getElementById("exMonth");
var exYear=document.getElementById("exYear");
var cardNumber=document.getElementById("cardNumber");

回答by decoder7283

Use inputmaskand moment.

使用inputmaskmoment

lets say you want a 10 year date range from today's date dynamically...

假设您希望动态地从今天的日期开始 10 年的日期范围...

include the jQuery.InputMask.js and moment.js library (CDN or self hosted)...

包括 jQuery.InputMask.js 和 moment.js 库(CDN 或自托管)...

Optional: CDN

可选:CDN

https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/bindings/inputmask.binding.js
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js

HTML

HTML

<input type="text" id="expires_mmyy" name="cc_expires" maxlength="5" />

JS

JS

$('#expires_mmyy').inputmask({
   alias: 'datetime', 
   inputFormat: 'mm/yy'
   min: moment().add(1, 'M').format('MM/YY'),
   max: moment().add(10, 'Y').format('MM/YY')
})

回答by Jaqtaris

I'm doing something very similar. The answers provided didn't work for my credit card expiry validation, but this one did. (I have used your variables)

我正在做一些非常相似的事情。提供的答案对我的信用卡到期验证无效,但这个答案有效。(我已经使用了你的变量)

if(exMonth.selectedIndex<month && exYear.selectedIndex<=year)
{
    alert("Please enter a valid expiration date");
    return false;
}