javascript 月份和年份的到期日

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5876474/
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-10-25 18:39:11  来源:igfitidea点击:

expiry date for month and year

javascriptdate

提问by Ghatzi

having some trouble trying to figure this out, complete novice when it come to JavaScript. I'm trying to validate a form, more specific the expiry date of a credit card. e.g jan 2011 would be invalid but dec 2011 would be valid etc. This is what i have so far:

在尝试解决这个问题时遇到了一些麻烦,当涉及到 JavaScript 时,完全是新手。我正在尝试验证表单,更具体地说是信用卡的到期日。例如,2011 年 1 月将无效,但 2011 年 12 月将有效等。这是我目前所拥有的:

function ExpiryDate() {

var year
var months

today = new Date();
    expiry = new Date(year, month);
    if (today.getTime() > expiry.getTime())

    return false;
else
    return true;
};

my form reads:

我的表格写着:

<form id="myform" method="post" action="default.html" onsubmit="return Validate(this);">

<p>Expiration Date: Month

<select name="ExpMon" id="ExpMon" title="select a month"> 
        <option value="1">Jan</option> 
        <option value="2">Feb</option> 
        <option value="3">Mar</option>
        <option value="4">Apr</option> 
        <option value="5">May</option> 
        <option value="6">June</option> 
        <option value="7">July</option> 
        <option value="8">Aug</option> 
        <option value="9">Sept</option> 
        <option value="10">Oct</option> 
        <option value="11">Nov</option> 
        <option value="12">Dec</option> 
 </select>      

 Year:
 <select name="ExpYear" id="ExpYear" title="select a year"> 
     <option value="2010">2010</option> 
     <option value="2011">2011</option> 
     <option value="2012">2012</option> 
     <option value="2013">2013</option>
     <option value="2014">2014</option> 
     <option value="2015">2015</option>
</select></p> 

</form

I'm not to sure how to use the id's to get what I want, any help would be appreciated, thanks in advance. note:I have a function called Validate which validates a text field in my form so i could attach it to this somehow.

我不确定如何使用 id 来获得我想要的东西,任何帮助将不胜感激,在此先感谢。注意:我有一个名为 Validate 的函数,它验证表单中的文本字段,因此我可以以某种方式将其附加到此。

采纳答案by Neil

var year = document.getElementById("ExpYear").value;
var month = document.getElementById("ExpMon").value;

If you prefer, you can use the names instead; you'd have to get Validate to pass the form element in as a parameter, but then you can use theForm.ExpYear.valueand theForm.ExpMonth.value.

如果您愿意,可以使用名称代替;您必须获得 Validate 才能将表单元素作为参数传入,但随后您可以使用theForm.ExpYear.valueand theForm.ExpMonth.value

Note: many people dislike statements of the form if (today.getTime() > expiry.getTime()) return false; else return true;when you can simply write return today.getTime() <= expiry.getTime();.

注意:if (today.getTime() > expiry.getTime()) return false; else return true;当您可以简单地编写return today.getTime() <= expiry.getTime();.

回答by alpian

Neil has answered your question about how to get the values (+1). I just wanted to add that, IMHO, it would be a better user experience not to allow your users to choose an unacceptable expiry date in the first place.

尼尔已经回答了您关于如何获取值 (+1) 的问题。我只是想补充一点,恕我直言,首先不允许您的用户选择不可接受的到期日期会更好的用户体验。

This is a little more effort but basically, by responding to the selected month you could look at the current time and then reset the allowable years based on that month. Similarly, based on the chosen year, the set of allowable months would change based on the current time.

这需要更多的努力,但基本上,通过响应所选月份,您可以查看当前时间,然后根据该月份重置允许的年份。类似地,根据所选年份,允许的月份集将根据当前时间更改。

Rather than letting the user make a mistake and then firing up a warning, just don't allow the mistake to be possible at all.

与其让用户犯错然后发出警告,不如让错误成为可能。

回答by NakedBrunch

The following will take the user input, create a date object, and then compare it to today's date. One key item is that it will find the last day of the current month so that even if today is May 3 and the user select "May 2011" (which is valid for a credit card transaction), it will return "valid".

下面将接受用户输入,创建一个日期对象,然后将其与今天的日期进行比较。一个关键的项目是它会找到当月的最后一天,这样即使今天是 5 月 3 日并且用户选择“2011 年 5 月”(这对信用卡交易有效),它也会返回“有效”。

function CheckDate() {
    var selectedDate = new Date (document.getElementById("ExpYear").value,document.getElementById("ExpMon").value)
    var nextmonth = selectedDate.setMonth(selectedDate.getMonth() + 1);
    var last_date_of_selected_date = new Date(nextmonth -1);
    var today = new Date();
    if (today > selectedDate) {
        alert("Invalid");
    }
    else {
        alert("Valid");
    }
}

Here's a working jsFiddle to see this in action: http://jsfiddle.net/cPApB/3/

这是一个正在运行的 jsFiddle,可以看到这一点:http: //jsfiddle.net/cPApB/3/

回答by Jefren Inocando

Try this:

试试这个:

var today = new Date();
var expDate = new Date($("#cart-expyear").val(),($("#cart-expmonth").val()-1)); // JS Date Month is 0-11 not 1-12 replace parameters with year and month
if(today.getTime() > expDate.getTime()) {
    console.log("Your Card is expired. Please check expiry date.");
}

回答by Santhosh

Use this simple validation

使用这个简单的验证

var expiryYear = $('#<%# DataBinder.Eval (ddlYear,"ClientID") %> option:selected').val();
var expiryMonth = $('#<%# DataBinder.Eval (ddlValidMonths,"ClientID") %> option:selected').val();
            var currentUserDate = $('#<%# DataBinder.Eval (hdnFieldJsonDate,"ClientID") %>').val();
            if (currentUserDate != null && expiryMonth != null && expiryYear != null) {
                currentUserDate = JSON.parse(currentUserDate);
                if (expiryMonth > 0 && expiryYear > 0) {

                    //If the Expiry Year smaller than Current Year, then validation failed
                    if (expiryYear < currentUserDate.Year)
                    { args.IsValid = false; }
                    //If the Expiry Year larger than Current Year, then validation passed
                    else if (expiryYear > currentUserDate.Year)
                    { args.IsValid = true; }
                    //If the Expiry Year is same as Current Year, and if Expiry Month is smaller than current month, then validation failes, else passed.
                    else if (expiryYear == currentUserDate.Year) {
                        if (expiryMonth < currentUserDate.Month)
                            args.IsValid = false;
                        else
                            args.IsValid = true;
                    }
                }
                else
                { args.IsValid = true; }
            }