最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript ddmmyyyy date check? - Stack Overflow

programmeradmin3浏览0评论

I've got a html form field where people can enter dates coded as such:

input type="text" name="dateofbirth" placeholder="dd/mm/yyyy"

I'm trying to find a JavaScript to check that the date is entered in the dd/mm/yyyy format (so 10 characters, 2/2/4)

Any comments would be appreciated. Only first time doing javascript and have been doing well until this hiccup.

Edit: code (form name is 'signup)

// JavaScript Document
function validateForm(signup) {
  {
    var x = document.forms["signup"]["dateofbirth"].value;
    var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
    if (x.match(reg)) {
      return true;
    }
    else {
      alert("Please enter dd/mm/yyyy");
      return false;
    }           
  }
}

I've got a html form field where people can enter dates coded as such:

input type="text" name="dateofbirth" placeholder="dd/mm/yyyy"

I'm trying to find a JavaScript to check that the date is entered in the dd/mm/yyyy format (so 10 characters, 2/2/4)

Any comments would be appreciated. Only first time doing javascript and have been doing well until this hiccup.

Edit: code (form name is 'signup)

// JavaScript Document
function validateForm(signup) {
  {
    var x = document.forms["signup"]["dateofbirth"].value;
    var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
    if (x.match(reg)) {
      return true;
    }
    else {
      alert("Please enter dd/mm/yyyy");
      return false;
    }           
  }
}
Share Improve this question edited Apr 17, 2012 at 16:21 Phrogz 303k113 gold badges667 silver badges756 bronze badges asked Apr 17, 2012 at 15:44 silentaurorsilentauror 811 gold badge1 silver badge4 bronze badges 8
  • 6 I don't mean to offend, but I don't think googling for scripts to use counts as "doing javascript" :-) Posting something you've tried and your HTML would give people a place to start. – Pointy Commented Apr 17, 2012 at 15:46
  • 1 There's a million possible approaches to this - being specific helps! (how many possible date fields are there? validating on submit or when the user enters text? what is the behavior when it isn't a valid entry?) – Snuffleupagus Commented Apr 17, 2012 at 15:50
  • @Pointy : well I'm just a student and the textbook wasn't useful so google was second option. I have literally tried almost every script that doesn't use any external libraries, arrays, php, .ASAP, or jQuery etc. I can only use javascript. nothing is working. – silentauror Commented Apr 17, 2012 at 15:52
  • @user1090190 : just the one date field named 'dateofbirth'. and validating onSubmit. when it's not valid then return false and Alert, something like "Invalid date format. Please enter dd/mm/yyyy" – silentauror Commented Apr 17, 2012 at 15:54
  • 1 @silentauror It sounds like you know the flow of what you need to do. Instead of googling for specific solutions why not google for specific problems you have when you implement your own solution? IE, "javascript hook onsubmit", "regex date", etc. Assembling the pieces should give you an idea of how it actually works and will help you down your path; copy and pasting a completed solution will not. – Snuffleupagus Commented Apr 17, 2012 at 16:01
 |  Show 3 more comments

6 Answers 6

Reset to default 7

You can validate date with your provided format via javascript using regular expression. sample code shown below.

function(input){
  var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
  if (input.match(reg)) {
    alert("Input matched");
  }
  else {
    alert("Please enter dd/mm/yyyy");
  }
}

ES6

const DDMMYYY_Validation = (input) : boolean=>{
  var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
  return !!input?.match(reg);
}

Have you looked at the Moment.js javascript library?

http://momentjs.com/

I haven't used it, but I plan to migrate my Javascript code to it.

The best JavaScript date library I have found is date.js at http://code.google.com/p/datejs/

It is also culture aware, so to validate your dd/mm/yyyy dates (I assume you are not located in the USA), use Date.parse as follows

var d1 = Date.parse("01/12/2004"); // returns a valid JavaScript date
var d2 = Date.parse("30/02/2004"); // returns null

validate Date includes all roles such as 28 feb and 29 in leep year

function leapYear(year) {
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}



function validateDayMonth(day, month, year) {
        var months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        var days = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
        if (months.indexOf(month) != -1 && days.indexOf(day) != -1) {
            if ((month == '02' && day == '29' && leapYear(year) == false) || (month == '02' && day == '30') || (month == '02' && day == '31') || (month == '04' && day == '31') || (month == '06' && day == '31') || (month == '09' && day == '31') || (month == '11' && day == '31')) {
                return false;
            } else {
                var GivenDate = year + '-' + month + '-' + day;
                var CurrentDate = new Date();
                GivenDate = new Date(GivenDate);
                if (GivenDate > CurrentDate) {
                    return false;
                } else {
                    return true;
                }
            }
        } else {
            return false;
        }

    }

Look over MDN guide for regular expressions. You will need info on character class that matches digit - search for "Matches a digit character" phrase; and a way to specify exact length of match - search for "Matches exactly n occurrences of the preceding character" phrase in this guide.

Have you looked in the error console of your web browser to ensure no JS syntax or runtime errors are being raised? The JavaScript code that you appended to your question is not valid surprising (you have an extra { and } wrapping your function body).

Tip: When using a regex to test a string for validity, you should use if (regex.test(str)) and not if (str.match(regex)) for simplicity and performance and self-documentation.

Given your requirements, I would do this:

function isDDMMYYYY(str){
  return /^\d{2}/\d{2}/\d{4}$/.test(str);
}

However, I would personally change the requirements to allow users to enter one-digit days and months:

return /^\d{1,2}/\d{1,2}/\d{4}$/.test(str);
发布评论

评论列表(0)

  1. 暂无评论