What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999.

https://i.stack.imgur.com/0p6j3.jpg

I have tried adding a mask to InputProps in my datePicker, but it doesn't seem to be working properly.

``<DatePicker
      label={label}
      value={value}
      open={isOpen}
      onChange={onChange}
      onOpen={changeIsOpen(true)}
      onClose={changeIsOpen(false)}
      className={styles.box__picker}
      slotProps={{
        popper: { className: styles.box },
        textField: {
          helperText,
          error,
        },
      }}
      minDate={MIN_DATE}
      maxDate={MAX_DATE}
   />``

Answer №1

If you want to restrict the input year in @mui/x-date-pickers, you can do so by utilizing the minDate and maxDate properties. The minDate property sets the earliest selectable date, while the maxDate property sets the latest selectable date. In this scenario, set minDate to 1000 and maxDate to 2023. Additionally, include readOnly: true, to allow users to only select dates using a popup model.

Keep in mind that both minDate and maxDate expect Date objects, so ensure you convert your desired dates into Date objects before passing them as props. You can achieve this with the new Date() constructor. Here is the updated code:

<DatePicker
      label={label}
      value={value}
      open={isOpen}
      onChange={onChange}
      onOpen={changeIsOpen(true)}
      onClose={changeIsOpen(false)}
      className={styles.box__picker}
      slotProps={{
        popper: { className: styles.box },
        textField: {
          helperText,
          error,
          readOnly: true,
        },
      }}
      minDate={new Date(1000, 0, 1)}
      maxDate={new Date(2023, 12, 31)}
   />

Alternatively, you can also employ the moment.js package for this purpose:

minDate={moment('01-01-1000').toDate()}
maxDate={moment('12-31-2023').toDate()}

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

Using Next.js 13 for authentication between server-side components and a separate backend

Looking for guidance on how to execute API requests from Nextjs 13 to a separate Python backend. I am faced with two different scenarios: API request made from client-side component API request made from server-side component When the request originates ...

What is the best way to control the maximum text length within each cell of a React datatable?

Here is an example of a standard table format: <MaterialReactTable columns={columns} data={emailResults} enableColumnFilters={false} enableMultiRowSelection={false} onRowSelectionChange={setRowSelection} > I prefer not to alter the emailRe ...

Tips for accessing jQuery UI tab elements and adjusting visibility for specific panels

How can I retrieve the panel numbers of jQuery UI tabs and adjust their visibility using CSS? I am looking to identify the panel numbers of each tab and control the visibility of certain tabs. <div id="tabs"> <ul> <li><a href="#"> ...

Unleashing the Power of the "OR" Operator in Form Field Validation

The custom JavaScript function FormQuote_Validator is used to validate form fields. It should return the value "TRUE" and display an alert message if all three input fields are submitted without any numbers; otherwise, it should return the value "FALSE". ...

jQuery Plugin - iDisplayLength Feature

I am currently using DataTables version 1.10.10 and I am looking to customize the main plugin Javascript in order to change the iDisplayLength value to -1. This adjustment will result in displaying "All" by default on all data tables, allowing users to fil ...

Subpar resolution of PNG images displayed in HTML canvas

My attempt to draw a PNG image onto the canvas is resulting in poor quality. I am using the drawImage method as shown below: src = folder+self.cur+".png"; imageObj.src = src; imageObj.onload = function() { context.clearRect(0, 0, cv, ch), context.drawImag ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

TypeScript is failing to identify a correctly typed property

Currently, I am facing issues while converting a Material UI Dashboard from React to Typescript. The problem arises during TypeScript compilation where the property in question meets the criteria mentioned in the error message. To put it briefly, the compi ...

Organize data in a table using a dropdown selection menu

My data structure looks like this: $scope.friends = [ { name:'John', phone:'555-1212', age:10 }, { name:'Mary', phone:'555-9876', age:19 }, { name:'Mike', phone:'555-4321', age:21 }, { na ...

Dealing with date formatting can be a headache when it comes to different

For my project, I have incorporated angularJS and momentJS to handle the date formatting more efficiently. I am facing two specific scenarios: Retrieving dates from a database and displaying them in the user interface: The response I receive from the s ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows: import React, { useState, useEffect } from 'react'; ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Encountering an issue while attempting to assess a Meteor package within a local environment

Hello everyone! I'm a beginner in Meteor programming and currently following the online book discovermeteor.com. I recently came across a chapter that covers the creation of Meteor Packages. Excitedly, I proceeded to create my own package using the ...

How can I stretch a background image using jquery to cover the entire document instead of just the window

I have implemented a plugin called https://github.com/srobbin/jquery-backstretch to effectively stretch the background image. The problem arises when the content of the page is long enough to create a scrollbar. In this case, while scrolling, the backgrou ...

Encounter a 500 internal server error in a single API route while using Next.js

Seeking assistance with a 500 response issue in one of my Next.js API routes. My app is deployed on Vercel and I've configured the CORS using the vercel.json file as per Vercel documentation. All other API routes work fine, but there's an anomal ...

What is the best way to align a title above menu items within a Material UI app bar when using TypeScript and React?

Check out my current app bar design: app bar image Here is the inspiration for the app bar layout I'm aiming for (title above menu items): inspiration app bar goal This snippet showcases my code: import * as React from 'react'; // More cod ...