Verify a date format from a post response

Hello all, I have created a post request
which basically adds a user and an ID, when the response returns, it also passes back a date.

so response body looks like this.

    "data": {
        "name": "Fred Dibner",
        "date": "27-02-2020 01:08:51"
    "result": "32"

In the test, I have written

let moment = require ('moment');

pm.test("Date is present in correct format", function () {
    pm.expect('DD-MM-YYYY hh:mm:ss'));

However, whenever I run the test though the format returns correctly, I’m faced with the fact the seconds in the date/time different by 2 to 3 seconds and the test fails. I thought I was just asking for the format but it appears not. Does anyone know how I can just validate the date format regardless of what time the test ran or even was delayed by?

Mucho thanks in advance.

Hey @ChrisG9612,

Welcome to the community! :trophy:

If you’re just wanting to check that the format is correct, you could use the chai .match() function. This takes regular expressions so you will be able to add something to match this pattern.

let jsonData = pm.response.json();

pm.test("Date is present in correct format", function () {
    pm.expect(^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}$/);

Thank you this works when the separator is a - however this seems to fail of the date separator is /
thus checking a format for dd/mm/yyyy hh:mm:ss fails

You would need to escape that character.

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

This is a great site for testing regular expressions:

Your pretty close with your first try. I recommend using moments isValid() function.

moment(date, format, locale, strict).isValid() will return a boolean. locale and strictness are optional, in this case you want to strict to verify the date is exact.

pm.expect(moment(, 'DD-MM-YYYY hh:mm:ss', true).isValid()).is.true;
1 Like