Incorrect tsx date interpretation when dealing with years such as 0022

I am facing an issue with dates in tsx. The problem lies in the fact that when I set a date like 30/11/0022, it interprets the date as 30/11/1922, which is incorrect.

Here is the input element I have in tsx:

<FormikField name="Birthdate" disabled={FormState.loading}/>

The FormikField is defined as follows:

interface Props {
  name: string;
  autoFocus?: boolean;
  hidden?: boolean;
  disabled?: boolean;
  component?: React.Component;
  label?: string;
  className?: string;
  disableAutocomplete?: boolean; 
}

export const FormikField = ({ ...props }: Props) => {
  // code implementation
};

The Birthday type definition can be found here:

Birthdate:{
        type: 'date',
        defaultvalue: null,
        placeholder: 'Set your birthday',
        validations: yup.date()
                        .required('The field is needed')
                        .min(new Date(new Date().getFullYear() - 120, new Date().getMonth(), new Date().getDate()), 
                            'The birthday cannot be more than 120 years ago')
                        .max(new Date(new Date().getFullYear() - 1, new Date().getMonth(), new Date().getDate()),
                            'The birthday cannot be less than 1 year ago.')
    }

Is there any way to resolve this issue? Please note that I am using getFullYear()

Answer №1

Formik lacks built-in support for handling dates effectively and is gradually becoming less supported. The default onChange function in Formik only looks for the e.target.value property, which, even on a date input with type="date", will return a string.

This creates issues because now you are storing a string representation of a date in the form state, which is much more ambiguous than a true date object. At some point, this string may be converted back into a date, triggering JavaScript's default date parsing mechanism that has complexities when it comes to certain date formats.

It is preferable to store an actual date in your form state, which can be accessed using e.target.valueAsDate in the onChange function instead.

Therefore, we need to override the onChange function and verify if the field is a date type. If it is, custom code is used to set the field value as valueAsDate. Otherwise, the default Formik onChange function is executed.

Unique code block provided...

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

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Executing Functions from Imported Modules in Typescript

Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code: import * as mathFn from './formula/math'; export functi ...

Resolve the type of the combineLatest outcome in RxJS

Encountering this scenario frequently in Angular when working with combineLatest to merge 2 observables that emit optional values. The basic structure is as follows: const ob1: Observable<Transaction[] | null>; const ob2: Observable<Price[] | nul ...

AngularJS inputs using ng-model should be blank when in the pristine state

Check out this input element within an HTML form: <input ng-model="amount" /> Currently, the input displays as $scope.amount = 0 in the controller. I want to start with a blank input field instead. This way, users can easily input data without havi ...

Tips on converting a date string in the format 'dd/MM/yyyy' to a date type using TypeScript

I have attempted the following code in order to convert the date from 'yyyy-mm-dd' format to 'dd/MM/yyyy'. However, when I check the typeof() of the result, it shows that it is a string. Is there a method to convert it into only a date? ...

Error: The nested property of the dynamic type cannot be indexed

Within my coding project, I've devised an interface that includes various dynamic keys for API routes, along with the corresponding method and response structure. interface ApiRoutes { "auth/login": { POST: { response: { ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

The recent update from Angular version 5.2 to 7 has caused issues with Post methods

An issue has occurred with the type mismatch in the error handling function. It seems that the argument provided is not compatible with the expected parameter type within the Observable structure. GetFullAddress(addressModel: FullAddr ...

Turn off the standard caps lock tooltip in Internet Explorer input boxes

When using the login dialog on my password input in Internet Explorer, a default tooltip appears when caps lock is activated (other browsers do not have this feature). I am looking to remove this default tooltip without relying on JavaScript. Is there an a ...

Handling linting errors for getInitialProps return type in NextJS with Typescript

I've been grappling with this problem for an extended period, and despite numerous attempts, I haven't been able to resolve it. My issue revolves around a basic page named one.tsx. Its structure is as follows: The linting error that's plag ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...

Building an AngularJS Service with TypeScript that is Non-Singleton: A Step-by-Step Guide

I need help converting an AngularJS Typescript Service into a Non-Singleton. Can anyone provide guidance on how to achieve this? (Note: This is not the same as other questions that focus on achieving this in JS) I have included some simple pseudo code be ...

Breaking down an object using rest syntax and type annotations

The interpreter mentions that the humanProps is expected to be of type {humanProps: IHumanProps}. How can I properly set the type for the spread operation so that humanPros has the correct type IHumanProps? Here's an example: interface IName { ...

Guide on installing MathType plugins for CKEditor 5 in an Angular 8 environment

Encountering an issue while attempting to utilize MathType in CKEditor Error message at ./node_modules/@wiris/mathtype-ckeditor5/src/integration.js 257:98 Module parse failed: Unexpected token (257:98) A proper loader may be required to handle this file t ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

What is causing me to not receive a 404 error when dealing with an unhandled state?

Currently, I am utilizing $stateProvider to configure my states in the following manner: constructor($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider. state("something", { url: "/index.html" }) ...

Arranging an array of arrays based on the mm/dd/yyyy date field

Currently, I am facing an issue while attempting to sort data obtained from an API by date in the client-side view. Here is an example of the data being received: address: "1212 Test Ave" address2: "" checkNumber : "" city: "La Grange" country: "" email: ...