JavaScript: validate date field in form


You may often require serialization of a form in JS and parsing of it's data. Here is a nice recipe to validate date with browser default methods. I like it because of relative simplicity.

It works on a principle of parsing date's components. We will create a JavaScript Date object from it and check if it is the same as a parsed date string. Date components that are wrong will go out of rage. SO we will have them different from the existing strings. This method is based on that hack.

I use this only to validate the string itself. I am specifying a placeholder of an input field to minimise user possibility to make a mistake. And I usually force user to enter date in my format with this tool. Anyway it's a good idea to put any datepicker component also.

function validate_date(value) {
    /**********************************************
    *    Validating date in format dd/mm/yyyy
    **********************************************/
    var comp = value.split('/');
    var d = parseInt(comp[0], 10);
    var m = parseInt(comp[1], 10);
    var y = parseInt(comp[2], 10);
    var date = new Date(y,m-1,d);
    return (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d);
}

So I use this with jQuery Plugins like:

  • jQuery.mask() plugin (To specify the exact format of user entered data. In case they are entered by hand. It's useful to just type '01022013' and do not type nasty slashes, entering something like '01/02/2013'.
  • Bootstrap.datepicker(). Because I use bootstrap often. Or there are plenty of native jQuery or jQuery UI plugins for date picking.

Hope this helps someone. Comments?

Comments

  1. You may take a look at input "date" in html5 specs too.

    ReplyDelete
    Replies
    1. Thanks I'm using it already. But I have to be sure user have not cheated. And I need my date entered in a certain format. Like: 31/12/9999

      Delete

Post a Comment

Popular posts from this blog

Django: Resetting Passwords (with internal tools)

Time Capsule for $25

Vagrant error: * Unknown configuration section 'hostmanager'.