Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below:

zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$'));

The value provided is 20001915.

The definition seems correct, however when tested on an online checker (https://www.regextester.com/[enter link description here]1) it shows FALSE (due to incorrect month number - 19). Surprisingly, zod still considers this value as correct. I am wondering why?

Answer №1

One comment pointed out that the regular expression is correct, but it's essential to understand that while the regex checks the format, it doesn't validate the date itself for accuracy in real-world terms. For instance, "20001915" follows the correct format (YYYYMMDD), but it signifies the 19th month, which isn't valid. Therefore, an external online checker correctly identifies it as FALSE.

To ensure the date's validity, you can validate it separately using the following code snippet:

const dateString = "20001915";
const year = parseInt(dateString.substring(0, 4));
const month = parseInt(dateString.substring(4, 6)) - 1; // Months are 0-indexed
const day = parseInt(dateString.substring(6, 8));

const date = new Date(year, month, day);

if (
  date.getFullYear() === year &&
  date.getMonth() === month &&
  date.getDate() === day
) {
  console.log("Valid date.");
} else {
  console.log("Invalid date.");
}

Additionally, you can optimize the regex pattern like so:

^(19\d\d|20\d\d)(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

How can I dynamically update content using <router-outlet> on a secondary page?

When accessing my homepage, I want to see a header, footer, and the home-news-page displayed. Additionally, when I click on a link in the header, I would like the content of the home-news-page to change accordingly. Here is how my routing is currently set ...

Beware of potential issues with FontAwesomeIcon when incorporating it into a Typescript file

I'm currently working with NextJS and Typescript. I encountered an issue when trying to import FontAwesomeIcon like this <FontAwesomeIcon icon={faCheck as any} /> as it triggered a warning in the console stating "Warning: FontAwesomeIcon: Suppor ...

Error encountered during Typescript compilation: Type 'void' cannot be assigned to type 'Item[]'

Below are my typescript functions. When I edit in vscode, the second function does not show any error message. However, upon compilation, an error is displayed for the second function: error TS2322: Type 'Promise<void>' is not assignable t ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'

I have been using ...

Which symbol or character corresponds to the public "get symbol" method?

While going through some Typescript code, I came across a line that is giving me trouble to understand. const symbol = Symbol.for('symbolname'); class Something { public get [symbol]() { return true; } ... } I am confused abou ...

Could you specify the type of useFormik used in formik forms?

For my react formik form, I have created multiple components and now I am looking for the right way to pass down the useFormik object to these components. What should be the correct type for formik? Main Form const formik = useFormik({ ... Subcomponent ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

Mastering the art of connecting content within Prismic

I have been working on creating a mega menu for my website header, but I am encountering a type error. Has anyone else faced this issue before and how did you resolve it? I am currently importing the generated types from @/prismicio-types. Here is an exam ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Determining the inner type of a generic type in Typescript

Is there a way to retrieve the inner type of a generic type in Typescript, specifically T of myType<T>? Take this example: export class MyClass { myMethod(): Observable<{ prop1: string, ... }> { .... } } type myClassReturn = ReturnTy ...

Encountering the "G is undefined" error in Jquery when utilizing string.match

Currently, I am utilizing Jquery version 1.3 and have come across an issue with the code. In Firebug, I am receiving an error message stating: "G is undefined." var product = $("#id :selected"); // This pertains to a dropdown element var prodTxt = ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

Challenges arise with data updating following a mutation in @tanstack/react-query

As I work on building an e-commerce website using React, I have a specific feature where users can add products to their favorites by clicking a button. Following this action, I aim to update the profile request to display the user's information along ...

A step-by-step guide on how to simulate getMongoRepository in a NestJS service

Struggling with writing unit tests for my service in nestjs, specifically in the delete function where I use getMongoRepository to delete data. I attempted to write a mock but couldn't get it to work successfully. Here is my service: async delete( ...

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...