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

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Is there a way to find a substring that ends precisely at the end of a string?

Looking to rename a file, the name is: Planet.Earth.01.From.Pole.to.Pole.2006.1080p.HDDVD.x264.anoXmous_.mp4 I want to remove everything starting from 2006 onwards. I considered using JavaScript string methods to find the index of the unnecessary part an ...

Identifying duplicates with the power of Regular Expressions

I am currently working with a dataset that contains the following information: company_id, company_name, country 1, a Tech, germany 2, a Tech AG, germany 3, a Tech gmbh, germany 4, AF, germany 5, AF gmbh, vermany After assigning company IDs based on prel ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Automatic type inference for TypeScript getters

It appears that Typescript infers field types based solely on the private variable of a field, rather than taking into account the getter's return type union (1) or inferring from the getter itself (2): test('field type inference', () =& ...

Incorrect Column Header Display in React with Kendo-UI Grid

I have a React application using redux as state manager. In this application we are deciding to use Kendo Ui grids. The first test is Ok but we noticed that the columns are totally wrong. We define only 5 Columns to be displayed in the table but we noticed ...

To properly display a URL on a webpage using Angular, it is necessary to decode

After my console.log in Angular 5 service call to the component, I can see the correct data URL being displayed http://localhost:4200/inquiry?UserID=645 However, when it is inside an Angular for loop in the HTML template, it displays http://localhost:42 ...

What is the purpose of `{ _?:never }` in programming?

I've been going through some TypeScript code and I stumbled upon a question. In the following snippet: type LiteralUnion<T extends U, U extends Primitive> = | T | (U & { _?: never }); Can anyone explain what LiteralUnion does and clarif ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

Is it possible to execute a system command within an Ionic3 application?

How can I run a command from an app running in Chromium on Linux (or potentially Windows or Android in the future)? Why do you want to do this? To control, for example, some audio/TV equipment using cec-client. echo "tx 20:36" | cec-client RPI -s -d 4 ...

What is the optimal method for defining a JSON serialization format for a TypeScript class?

Currently, I am in the process of developing a program using Angular and TypeScript. Within this program, there is a specific class named Signal that consists of various properties: export class Signal { id: number; obraId: number; obra: string ...

Angular 14: Trouble with ngFor after latest update - Type 'unknown' causing issues

Just updated my project to angular version 14.0.4 Within the html of a component, I have the following code: <div class="file" *ngFor="let file of localDocumentData.files; index as i;"> <div class="card"> ...

Unable to classify mapRef.current

I am facing an issue with my react component that contains a leaflet map. TypeScript is warning me about line mapRef.current.setView(coords, 13), stating it is an "unsafe call of an any typed value" import 'leaflet/dist/leaflet.css'; import { Map ...

Will adding additional line breaks increase the overall length of the code?

Currently, I am immersed in a project involving Angular 4 and TypeScript. Recently, I came across a video showcasing how VSCODE can enhance the code's appearance. Intrigued, I installed the prettier plugin to achieve the same effect. Running this tool ...

Displaying the default value in a Material-UI v5 select component

I am looking to display the default value in case nothing has been selected yet for the mui v5 select component below, but currently it appears empty... <StyledCustomDataSelect variant='outlined' labelId='demo-simple- ...

Typescript library available as a private npm dependency

I have developed a Typescript library that I bundle as an npm module. During the development of my frontend application, I easily integrated this library using yarn link. As I set up GitLab CI for other developers to work on the frontend application, I am ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

In Typescript, encountering a member of a union type with an incompatible signature while utilizing the find method on an array of

I need to verify if a specific value exists within an array of objects. The structure of my array is as follows: [ 0: { id: 'unique_obj_id', item: { id: 'unique_item_id', ... }, ... }, 1: {...} ] The objects in the ar ...

Is your Angular app missing i18next translations?

Can Angular's i18next provider be configured to hide any value when the key is not defined? The issue arises when there is no translation defined for a specific key like my:key. I want to display an empty string in the template instead of showing the ...

Create an HTML button on the homepage that directs users to the "about" page

I've been struggling to make a button in my Ionic app navigate to a different page upon clicking. Despite being new to Ionic, I've spent hours trying to solve this issue. Below is the HTML code in home.page.html: <ion-header> &l ...