regexpostmanpostman-testcase

How to write a script to check whether the date format is correct or not


Below is the array I got in postman. I have to write a script to check the date format is correct or not. can anyone please help.

[
   {
      "sportName":"cricket",
      "sportId":"1.923",
      "nextSportDateTime":"2023-01-14T12:30:00.000Z"
   },
   {
      "sportName":"football",
      "sportId":"1.922",
      "nextSportDateTime":"2023-01-18T12:30:00.000Z"
   },
   {
      "sportName":"table tennis",
      "sportId":"1.924",
      "nextSportDateTime":"2023-01-23T12:30:00.000Z"
   }
]

So far I've tried

this pm.test('Check the date format', () => {
    _.each(jsonData.body,(item)=>{
    pm.expect(item.nextSportDateTime).to.match(/^\d{4}-\d{2}-\d{2}-\`T`\d{2}:\d{2}:\d{2}:\d{3}$/);
    });
})

It didn't work


Solution

  • This Regex will do it: ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$.
    See https://regex101.com/r/MBbe31/1

    You missed the Z at the end.
    Also I'm not sure why you put a dash - before the T and backkticks around it.