0

Does anybody know how I can make the forwardslash and format: dd/mm/yyyy compulsory in this regex?

// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function isValidDate(s) {
    // format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
    if (dateFormat.test(s)) {
        // remove any leading zeros from date values
        s = s.replace(/0*(\d*)/gi,"$1");
        var dateArray = s.split(/[\.|\/|-]/);
              // correct month value
        dateArray[1] = dateArray[1]-1;
        // correct year value
        if (dateArray[2].length<4) {
            // correct year value
            dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
        }
        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
        if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}
1

2 Answers 2

1

for mandatory dd/mm/yyyy try:

 var dateFormat = /^\d{2}\/\d{2}\/\d{4}$/;

I didn't look to closely at the rest of the function, but I think that is what you were going for.

Sign up to request clarification or add additional context in comments.

1 Comment

hehe .. same thing same time :)
0

this would do it i think..

/^\d{2}\/\d{2}\/\d{4}$/

forced 2 digit days, 2 digit months, 4 digit years and / as seperator..

or

/^[0-3][0-9]\/[0-1][0-9]\/\d{4}$/

to enforce a little bounds control..
day: 00-39
month: 00-19

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.