Home > Enterprise >  Regex date validation yyyy-mm-dd returns null Javascript
Regex date validation yyyy-mm-dd returns null Javascript

Time:10-29

I'm testing out my regex validator using js, I've tested the regex in tester it is valid but I think the problem is with my code, I'm fairly new to JS. Hoping someone can help me on this one. Thank you

So this is the input string that I use, then I tokenize the returned value to each string it's a valid yyyy-mm-dd format to check if it's a date.

project = "HRT: Human Resource Ticketing" AND (("Time to first response" = breached() OR "Time to resolution" = breached()) AND resolution = Done AND "Request Type" = "Payroll Dispute (HR)") AND (createdDate >= 2022-10-1 AND createdDate  <= 2022-10-31)
const items = token.split(" ");
    for (const item of items) {
    console.log(item.match("([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))"))
}

I don't know why it returns null, BTW I just need to capture the date so I can replace the date with whatever I want. Thank you

CodePudding user response:

Just change the string "" to a regex expression //. Instead of "([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))", change it to this: /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/.

It should, for example, return the following array:

[
  '2022-10-31',
  '2022-10-31',
  '10',
  '31',
  index: 0,
  input: '2022-10-31)',
  groups: undefined
]

Where you can access the matched value by item[0].

So the new code is as follows:

const token = `HRT: Human Resource Ticketing" AND (("Time to first response" = breached() OR "Time to resolution" = breached()) AND resolution = Done AND "Request Type" = "Payroll Dispute (HR)") AND (createdDate >= 2022-10-1 AND createdDate  <= 2022-10-31)`
const regex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/

const items = token.split(" ");
    for (const item of items) {
    const match = item.match(regex)
    if (match) console.log(match[0])
}
  • Related