Recent

Tuesday, January 4, 2022

Date Format Validation in Javascript

 


There’re several different ways to handle Date values through the script, all depends on the exact need. In some cases, there’s a need to enter a date value manually, as text, yet to force it to be in a specific valid date format.


Below is the javascript code to valdate date with given format. Add this code inside the script tag


function ValidateDate(dt, format) {

    var isValid = true;

    if(dt.length != format.length) {
        isValid = false;
    }

    format = format.replace(/\ /g, "/").toLowerCase();
    dt = dt.replace(/\ /g, "/");
    var dateFormat = dt;
    //Get Day Value
    var day = 0;
    if(format.indexOf("dd") > -1) {
        var index = format.indexOf("dd"),
        day = dt.substring(index * 1 + 2);
      dateFormat=  dateFormat.replaceAt(index, "dd");

    } else if(format.indexOf("d") > -1) {
        var index = format.indexOf("dd"),
        day = dt.substring(inde, index * 1 + 1);
       dateFormat=  dateFormat.replaceAt(index, "d");
    } else {
        isValid = false;
    }

    //Get Month Value
    var month = 0;
    if(format.indexOf("mmm") > -1) {
        var index = format.indexOf("mmm"),
        month = dt.substring(index, index * 1 + 3);
      dateFormat=   dateFormat.replaceAt(index, "mmm");
    } else if(format.indexOf("mm") > -1) {
        var index = format.indexOf("mm"),
        month = dt.substring(index, index * 1 + 2);
       dateFormat=  dateFormat.replaceAt(index, "mm");
    }
    else {
        isValid = false;
    }

    var year = 0;
    if(format.indexOf("yyyy") > -1) {
        var index = format.indexOf("yyyy"),
        year = dt.substring(index, index * 1 + 4);
       dateFormat=  dateFormat.replaceAt(index, "yyyy");
    } else if(format.indexOf("yy") > -1) {
        var index = format.indexOf("yy"),
        year = dt.substring(index, index * 1 + 2);
      dateFormat=   dateFormat.replaceAt(index, "yy");
    }
    else {
        isValid = false;
    }

    if(dateFormat != format)
    {
        isValid = false;
    }

    console.log(day);
    console.log(month);
    console.log(year);
	console.log(isValid);

}
String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

ValidateDate("12-07-2017", "MM-DD-YYYY");
ValidateDate("12-07-2017", "DD/MM/YYYY");
ValidateDate("2017-07-12", "YYYY-MM-DD");
 

No comments:

Post a Comment