简体   繁体   中英

date format with “mm/dd/yyyy” in text

I have the following code, using the format mm/dd/yyyy...

var required = "";
var dob = $("#txtDOB").val();
if (dob != "") {
   var myDate = new Date(dob);
   var today = new Date();
   var maxDOB = new Date("01/01/1900");
   if (myDate > today || myDate < maxDOB) {
      required += "Invalid Birth Date \n";
   }
}

There is no error if the user enters 22/22/1982. How do I validate this?

Try Datejs - An open-source JavaScript Date Library

Date.parse("22/22/1982") returns null

It's a little extra overhead @ ~25 kb but it's powerful when you need to work with dates

您是否要用AND运算符( && )代替OR( || )?

if (myDate > today || myDate < maxDOB) {
String.prototype.isValidDate = function(){  
    var arrDate = this.split("/");  
    if(arrDate.length!=3)return false;  
    var dateComp = new Date(arrDate[2], arrDate[0]-1, arrDate[1]);  
    return (arrDate[0] == dateComp.getMonth()+1 &&  
            arrDate[1] == dateComp.getDate() &&  
            arrDate[2] == dateComp.getFullYear());  
}; 
function validMdy(str){
    var d, A= str.split(/\D+/);
    if(A[0]> 12) throw 'bad Month';
    d= new Date(A[2], A[0], 0);
    // expects month 1-12
    if(d.getDate()<A[1]) throw 'bad Date';

    return new Date(A[2], A[0]-1, A[1]);
}
var s= "22/22/1982"; // "2/29/2011"
validMdy(s)

I managed to use the regex date (mm/dd/yyyy) with the if (dob.match(re)). I got some good answers, but they were somewhat more complex than I would like.

var required = "";
var dob = $("#txtDOB").val();
var re = /^((0[0-1]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/]([0-9]{2}|[0-9]{4}))$/;
if (dob != "") {
    if (dob.match(re)) {
        var myDate = new Date(dob);
        var today = new Date();
        var maxDOB = new Date("01/01/1900");
        if (myDate > today || myDate < maxDOB) {
            required += "Invalid Birth Date \n";
        }
   }
            else { required += "Invalid Date Format \n"; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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