简体   繁体   English

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

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

I'm a complete Javascript beginner and I'm really stuck on my assignment.我是一个完整的 Javascript 初学者,我真的被我的任务困住了。 I have to get the user to enter credit card details and validate them with Javascript.我必须让用户输入信用卡详细信息并使用 Javascript 验证它们。 Here are my problems.这是我的问题。

  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.当您不选择任何内容时,付款类型返回 false(这是我想要它做的),但我使用了类似的到期月份和年份代码,即使您不选择,这两个也可以返回 true一个选择,我希望他们返回 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.信用卡号验证脚本(需要 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> 

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;
}

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");

I found a problem with the previous answer.我发现上一个答案有问题。 I'm posting here my tested solution.我在这里发布我经过测试的解决方案。

The problem with the previous answers they are not considering the day.他们没有考虑以前的答案的问题。 For solve it you must use the last day of the month.要解决它,您必须使用该月的最后一天。 To find it in Javascript you can use setFullYear(year, month, day) where the day is zero.要在 Javascript 中找到它,您可以使用 setFullYear(year, month, day) ,其中日期为零。

Bonus: month in javascript is 0 - 11奖励:javascript 中的月份是 0 - 11

But when you set a month you shouldn't use month - 1.但是当您设置月份时,您不应该使用月份 - 1。

Ex: setFullYear(2020, 6, 0) // -> 31 Jun 2020.例如:setFullYear(2020, 6, 0) // -> 2020 年 6 月 31 日。

const today = new Date();
const ed = new Date();
ed.setFullYear(year, month, 0);

if (ed < today) {
}

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;
}

Use inputmask and 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')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM