noclist
noclist

Reputation: 1819

Auto format input to date using javascript

I have some javascript that autoformats user input into an SSN (ddd-dd-dddd) I'm having trouble converting this script to support a date format (mm/dd/yyyy)

    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    if (val.length > 4) {
        this.value = val;
    }
    if ((val.length > 3) && (val.length < 6)) {
        newVal += val.substr(0, 3) + '-';
        val = val.substr(3);
    }
    if (val.length > 5) {
        newVal += val.substr(0, 3) + '-';
        newVal += val.substr(3, 2) + '-';
        val = val.substr(5);
    }
    newVal += val;
    this.value = newVal;

Would someone be able to explain how this is working and show me how to convert it to my date format?

Upvotes: 1

Views: 2129

Answers (1)

DonovanM
DonovanM

Reputation: 1198

The code you posted removes all non-numeric characters from this.value and then adds a "-" in the correct places depending on the length of the string.

Here's my attempt at an easier to understand version of that for dates:

function insertString(originalString, newString, index) {
    return originalString.substr(0, index) + newString + originalString.substr(index);
}

function formatDate(dateString) {
    var cleanString = dateString.replace(/\D/g, ''), // Removes all non-numeric characters
        output = cleanString.substr(0, 8), // Limit to 8 digits
        size = dateString.length;

    if (size > 4)
        output = insertString(output, '/', 4);

    if (size > 2)
        output = insertString(output, '/', 2);

    return output;
}

Then in your handler you only need to do this:

this.value = formatDate(this.value);

Upvotes: 2

Related Questions