DatePicker using React Hook Form not displaying format correctly - reactjs

I'm using DatePicker in side a react hook form.
I'm able to get my form to display the Date I pick but it's not in the format I'm expecting.
The text box the is correct August 19, but when I try to get it to display using
it comes back at as this format 2022-09-19T23:51:47.000Z
I'm not sure what I'm missing as i'm pretty stump at the moment on what needs for it to display correctly.
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Controller
name="Date"
control={control}
defaultValue=""
rules={{
required: { value: true, message: "Date is required" },
}}
render={({ field }) => (
<DatePicker
openTo="month"
views={["month", "day"]}
label="month and date"
value={field.value}
onChange={(e, data) =>
field.onChange(data);
}
inputFormat="MMMM dd"
renderInput={(params) => (
<TextField {...params} helperText={null} />
)}
{...field}
/>
)}
/>
</LocalizationProvider>

If you're using date-fns you can do this with the ISOString:
format(new Date('2022-09-19T23:51:47.000Z'), 'MMMM DD', { locale: 'US' });
It would return:
September 19

Related

Convert DatePicker value in material ui

I have a form with a datePicker input from material-ui
When I pick a date and submit my form, if I console.log my data I will receive 'Tue Jan 10 2023 10:31:48 GMT+0100 (Central European Standard Time)' i want to received '01/11/2023'
I would like to format the data received.
Here my DatePicker :
const [deadLine, setDeadLine] = useState(new Date());
<Controller
name="deadLine"
defaultValue={deadLine}
control={control}
render={({ field: { onChange, ...restField } }) => (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Request Date"
onChange={(event) => {
console.log(event);
onChange(event);
setDeadLine(event);
}}
renderInput={(params) => <TextField {...params} />}
{...restField}
/>
</LocalizationProvider>
)}
/>
I have already tried :
To Use "format="dd-MM-yyyy"" from material-ui, but it only change the
visual not the data received.
To use moment with
setDeadLine(moment(event.target.value).format('MM/DD/YYYY'));,
still received the initial value.
To know : I am using react-hook-form
First of all to use moment you should wrap you DatePicker with moment Adapter:
<LocalizationProvider dateAdapter={AdapterMoment}> more also, onChange return the value you shouldn't access it with event.target.value, but you have directly the value with moment(value).format('DD/MM/YYYY') and of course don't forget to import Adapter Moment - import { AdapterMoment } from '#mui/x-date-pickers/AdapterMoment';
It should look like that:
<LocalizationProvider dateAdapter={AdapterMoment}>
<DatePicker
label="Request Date"
onChange={(value) => {
setDeadLine(moment(value).format('DD/MM/YYYY'));
}}
renderInput={(params) => <TextField {...params} />}
{...restField}
/>
</LocalizationProvider>

Setting "DD/MM/YYYY" format in MUI

In my MUI form I'm using DatePicker to select dates for departure and return of users. But when I used .toLocaleDateString() it set my dates in mm-dd-yyyy format. But I wanted to set them as dd-mm-yyyy format. For that I've passed 'en-GB' as parameter in .toLocaleDateString(). But in the DatePicker TextField it shows a red border Like this and the pre-defined date (from the state) are also gone. Without the parameter it shows This which is the mm-dd-yyyy format. From the similar previous questions I even tried it through moment package and set the dt variable as moment(new Date()).format("DD/MM/YYYY") but it is still showing red border around the text field. I know this question was asked a lot of times before and I went through all of them and got no solution.
Date picker
const dt = new Date().toLocaleDateString();
console.log(dt);
const [formData, setFormData] = useState({
from: "",
to: "",
depart: dt,
return: dt,
noOfPassenger: 1,
tripType: "Return",
});
{/* App component */}
<div className="dates">
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Departure Date"
disablePast
onChange={(e) =>
setFormData({
...formData,
depart: e.toLocaleDateString(),
})
}
value={formData.depart}
renderInput={(params) => <TextField {...params} required />}
/>
</LocalizationProvider>
</div>
In my case I used a DateRangePicker, but it's the same across all pickers.
Just set the inputFormat like here:
<DateRangePicker
startText={t`From`}
endText={t`To`}
value={dateValue}
inputFormat="dd.MM.yyyy"
onChange={(newValue) => {
setDateValue(newValue);
console.log(newValue);
}}
renderInput={(startProps, endProps) => (
<React.Fragment>
<TextField {...startProps} />
<TextField {...endProps} />
</React.Fragment>
)}
/>
Emanuel Avram has already given a good answer. I will just add.
The value (date) of the component must have the same format defined internally, so it's no use using "toLocaleString()" without changing the internal format. Use the "inputFormat" property.
// "dd" = "Su", "Mo", ..., "Sa"
// "DD" = "01", "02", ..., "31"
inputFormat="dd/MM/YYYY" // Tu/09/2022
inputFormat="DD/MM/YYYY" // 09/13/2022
<DatePicker
label="Departure Date"
inputFormat="DD-MM-YYYY" // 13-09-2022
onChange={(e) =>
setFormData({
...formData,
depart: e.toLocaleDateString(),
})
}
value={formData.depart}
renderInput={(params) => <TextField {...params} required />}
/>

why MUI datepicker not working in production?

I'm using MUI datepicker along with React hook form, I'm using #mui/lab/AdapterMoment as date adaptor.
In local environment, datepicker's onChange is working fine. But when it is built and deployed in production, onChange is not working so if I click on a date nothing is happening. I tested react hook and it seems to be working fine. Can anyone help me figure out this issue?
<LocalizationProvider dateAdapter={DateAdapter}>
<Controller
name="reminderFromDate"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<div className="reminder_form_err_container remeberFieldInput">
<DatePicker
className="login_input remeberFieldInput ip-field w-100 "
label="Date"
mask="___ __ ___, ____"
inputFormat={"ddd D MMM, YYYY"}
value={value}
disablePast
readOnly
onChange={(e) => onChange(e)}
renderInput={(params) => (
<TextField
{...params}
onClick={(e) => setStartDate(true)}
/>
)}
open={isStartDate}
onClose={() => setStartDate(false)}
/>
{errors.reminderFromDate && (
<span className="reminder_text-danger" role="alert">
{"This field is required"}
</span>
)}
</div>
)}
/>
</LocalizationProvider>

react-datepicker and react-hook-forms: required not working

React-datepicker and react-hook-form. I am trying to make react-datepicker required, but its not working
<Controller
name="resetDateTime"
control={control}
required
render={({ field }) => (
<Datetime
onChange={(date) => field.onChange(date)}
selected={field.value}
inputProps={{
placeholder: "MM-DD-YYYY HH:mm",
}}
viewMode="time"
/>
)}
/>
{errors.resetDateTime && <span>This field is required</span>}
When I submit form without selecting any datetime, I am expecting the error to be show, but instead it submits the form
<Controller /> has no required prop, instead of you have to pass the validation rules via the rules prop. Check the docs for more info.
<Controller
name="resetDateTime"
control={control}
rules={{ required: true }}
render={({ field }) => (
<Datetime
onChange={(date) => field.onChange(date)}
selected={field.value}
inputProps={{
placeholder: "MM-DD-YYYY HH:mm",
}}
viewMode="time"
/>
)}
/>
{errors.resetDateTime && <span>This field is required</span>}

How to validate KeyboardDatePicker with react-hook-form when date is invalid

I am validating a material UI KeyboardDatePicker with react-hook-form:
<Controller
name="endDate"
control={control}
defaultValue={new Date()}
rules={{
required: "End date is required"
}}
render={({ field, fieldState }) => {
return (
<KeyboardDatePicker
autoOk
variant="inline"
inputVariant="standard"
label="End Date"
format="MM/dd/yyyy"
value={field.value}
InputAdornmentProps={{ position: "start" }}
onChange={() => {
field.onChange();
}}
error={(!!fieldState.error || field.value === 'Invalid Date')}
helperText={
fieldState.error ? fieldState.error.message : null
}
/>
);
}}
/>
It works fine and throws the message "End date is required" if KeyboardDatePicker is empty. However I also need to throw an error message "Invalid date format" if user edits the date and removes a couple of characters like '06/01/2021' to '06/01/20__'. This functionality works built-in and works fine in isolation i.e. if I don't combine date picker with react-hook-form.
However I am not getting how to achieve this in combination with react-hook-form. I tried to modify helperText but to no avail.
This is how I do it :
<Controller
name="endDate"
control={control}
defaultValue={new Date()}
rules={{ required: true }}
render={({ field: { ref, ...rest } }) => (
<KeyboardDatePicker
margin="normal"
id="date-picker-dialog"
format="dd/MM/yyyy"
disablePast={true}
initialFocusedDate={Date.now()}
KeyboardButtonProps={{
"aria-label": "change end date",
}}
invalidDateMessage={"End date is required"}
{...rest}
/>
)}
/>

Resources