6

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;
    }           
  }
}
Phrogz
  • 296,393
  • 112
  • 651
  • 745
silentauror
  • 71
  • 1
  • 1
  • 4
  • 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 Apr 17 '12 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 Apr 17 '12 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 Apr 17 '12 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 Apr 17 '12 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 Apr 17 '12 at 16:01
  • @user1090190 : well this is not the first validation I've coded for this project. I've done email, phone numbers, alphabetical etc. I used minimal help for those, just what I remember from lectures and classes. and I applied the same principals for this validation and it JUST WON'T WORK! That's when I resorted to google. – silentauror Apr 17 '12 at 16:05
  • @silentauror (I'm probably coming across as a dick, that's not my intent at all) Whenever you post a question if you have relevant code you should post it. If you post your original code snippet we can explain to you why it doesn't work and what you need to do to fix it, so next time you know how to handle it. :o) – Snuffleupagus Apr 17 '12 at 16:07
  • @user1090190 : no not at all. I'm working on two computers and now in the process of copying my code to the question. just have to get it across computers – silentauror Apr 17 '12 at 16:11

6 Answers6

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);
}
Community
  • 1
  • 1
irfanmcsd
  • 6,533
  • 7
  • 38
  • 53
1

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.

nickk_can
  • 345
  • 3
  • 11
1

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
ron tornambe
  • 10,452
  • 7
  • 33
  • 60
0

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.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
0

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);
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • sorry I am really quite a newbie to javascript... where would I implement this: return /^\d{2}/\d{2}/\d{4}$/.test(str); ?? – silentauror Apr 17 '12 at 16:37
  • @silentauror If you don't want to wrap it up as a function like I did (in the first code sample; the second was just me not repeating myself) then you could use `var isValidLookingDate = /.../.test(str);` – Phrogz Apr 17 '12 at 16:46
  • like this? `{ var x= document.forms["signup"]["dateofbirth"].value; var isvalid = /^\d{1,2}/\d{1,2}/\d{4}$/.test(x); if (isvalid.match(x)) { return true; } else { alert("Please enter dd/mm/yyyy"); return false; }` getting a syntax error and it's not working.. now I'm just confusing myself. this is so frustrating. (ps. cant get spaces in the comment but it's formatted properly in terms of spaces and indent) – silentauror Apr 17 '12 at 16:52
0

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

    }
Mostafa Mahmoud
  • 153
  • 3
  • 7