1

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?

1
  • On different tack, might take a look at moment.js lib. Lots of functionality for manipulating dates. Commented Dec 18, 2015 at 16:24

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.