31 March 2016

Validate a date - the simple way

 

 Introduction

How do you check if a date is valid? Let's see... Does the month selected has 30 or 31 days. But wait... there is the february it has only 28 days. And all 4 years there is a leap year. Except every 100 years. Pretty complex, isn't it?
But, there is a simple way!

How it works

Funny thing about Javascript is that you can create a date even with invalid values. It converts it into a valid date.
For example. If you want to create the date 32nd of March, it will make the 1st of April out if it. So all we have to do is to check if we get the date, we put in.

Requirements

None. Only JS itself.

Code

    function checkDate(year, month, day) {
        var d = new Date(year, month - 1, day);
        return d.getFullYear() == year && (d.getMonth() + 1) == month && d.getDate() == day;
    }

    checkDate(2016, 2, 28); // returns true
    checkDate(2016, 7, 35); // returns false

10 March 2016

Working with GET-Parameters

 Introduction

 Working with Get-Parameters from the url can be very usefull. Recieving those parameters can be a pain in the ass. Here is a simple function that does the trick. So if you want to know the value of the parameter "q", it's in param("q").

Arguments

 The name of the parameter to search for

Returns 

 The value of the parameter (undefined, if the parameter is not existend or empty)

 Requirements

This function doesn't require anything then JS itself. Can even work without jQuery.

Code

 function param() {
    var searchstring = window.location.search;
    if (!searchstring) {
        // search is empty
        return undefined;
    }
    // search 
    var part = searchstring.search("&" + arguments[0] + "=");
    if (part == -1) {
        part = searchstring.substring(1).search(arguments[0] + "=");
        if (part == -1) {
            return undefined;
        }
    }
    // found!
    searchstring = searchstring.substring(part + 1);
    part = searchstring.search(/&/);
    if (part > -1) {
        searchstring = searchstring.substring(0, part);
    }
    part = searchstring.search(/=/);
    searchstring = searchstring.substring(part + 1);
    return searchstring;
}