-2

How to use this regular expression to validate the date in this case?

var regex = new RegExp(/[\d-: ]/, 'g');
console.log(regex.test(updated_post_datetime));

The input will be something like that 2011-03-29 12:22somestring It has to return false in that case, but it returns true.

Sean Bright
  • 114,945
  • 17
  • 134
  • 143
Svetlozar
  • 937
  • 1
  • 9
  • 22

3 Answers3

2

If you e.g. add ^, + and $ it will work, where

"^"  =  from the beginning of the line
"+"  =  one or more of chosen character
"$"  =  to end of line

var regex = /^[\d-: ]+$/;
console.log(regex.test("2011-03-29 12:22somestring"));
console.log(regex.test("2011-03-29 12:22"));
console.log(regex.test("2011-03-30 12:22"));
console.log(regex.test("2011-04-01 12:22"));
console.log(regex.test("2011-05-19 12:22"));

Do note though, this will return true for e.g. 123 as well, so if you intend to validate that it is really a date, you need something like one of these:

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Asons
  • 81,773
  • 12
  • 93
  • 144
0

An alternative approach:

console.log(!isNaN(Date.parse(updated_post_datetime)));
Jos
  • 412
  • 4
  • 9
0

You can try

var regex = new RegExp(/^(?:[12]\d{3})-(?:(0[1-9])|(1[0-2]))-(?:([0-2][1-9])|(3[0-1]))\s+(([01][1-9])|(2[0-3])):([0-5][0-9])|(2[0-3])/, 'g');
console.log(regex.test(updated_post_datetime));

or better try to create a new date for it

var test1 = '2011-03-29 12:22';
console.log(test1 + ' test is: ' + isDate(test1));

var test2 = '2011-02-29 25:61:73';
console.log(test2 + ' test is: ' + isDate(test2));

function isDate(value) {
    if (!value) return false;

    try {
        var dt = new Date(value);
        return dt instanceof Date && !isNaN(dt.valueOf())
    }
    catch (e) {
        return false;
    }
}

because validating date with regular expression alone is not enough