[英]min and max date not working on formik/material-ui/datepicker component
This is driving me crazy.这真让我抓狂。 I can't get min and max date to work at all.
我根本无法获得工作的最小和最大日期。 Here's my code:
这是我的代码:
<DatePickerField
name={dob.name}
label={dob.label}
format="MM/DD/YYYY"
minDate={new Date('12/31/1920')}
maxDate={new Date()}
fullWidth
onChange={(event, newdate) => { currentAge = calculateAge(newdate, currentAge); }}
/>
No matter what date I use, like 1/1/1800, it shows up in the input field for the date picker and the age shows up as 220 years old (as an example).无论我使用什么日期,例如 1800 年 1 月 1 日,它都会显示在日期选择器的输入字段中,并且年龄显示为 220 岁(例如)。 Same goes if I pick a date in the future.
如果我选择未来的日期也是如此。 Age shows up as -whatever.
年龄显示为-whatever。 The calucateAge function is working fine, but DatePickerField is accepting ANY date.
calucateAge function 工作正常,但 DatePickerField 接受任何日期。
Why is it not forcing a min and max date?为什么不强制设置最小和最大日期?
EDITED TO ADD BELOW:编辑添加如下:
This is the DatePickerField I am using that I adapted from Formik:这是我使用的从 Formik 改编的 DatePickerField:
import React, { useState, useEffect } from 'react';
import { useField } from 'formik';
import Grid from '@material-ui/core/Grid';
import DateFnsUtils from '@date-io/date-fns';
import {
MuiPickersUtilsProvider,
KeyboardDatePicker
} from '@material-ui/pickers';
const DatePickerField = props => {
const [field, meta, helper] = useField(props);
const { touched, error } = meta;
const { setValue } = helper;
const isError = touched && error && true;
const { value } = field;
const [selectedDate, setSelectedDate] = useState(null);
//console.log("datepickerfield" + JSON.stringify(field) + "end of datepickerfield");
useEffect(() => {
if (value) {
const date = new Date(value);
setSelectedDate(date);
}
}, [value]);
function _onChange(date) {
if (date) {
setSelectedDate(date);
try {
const ISODateString = date.toISOString();
setValue(ISODateString);
} catch (error) {
setValue(date);
}
} else {
setValue(date);
}
}
return (
<Grid container>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
{...field}
{...props}
variant="inline"
format="MM/dd/yyyy"
value={selectedDate}
onChange={_onChange}
error={isError}
invalidDateMessage={isError && error}
helperText={isError && error}
disableToolbar
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</MuiPickersUtilsProvider>
</Grid>
);
}
export default DatePickerField;
At this point I don't know if the problem lies in the call or the DatePickerField.jsx file itself.此时我不知道问题出在调用还是 DatePickerField.jsx 文件本身。
Any help would be truly appreciated!任何帮助将不胜感激!
You need to use strings and not a date您需要使用字符串而不是日期
<DatePickerField
name={dob.name}
label={dob.label}
format="MM/DD/YYYY"
minDate={new Date('12/31/1920').toString()}
maxDate={new Date().toString()}
fullWidth
onChange={(event, newdate) => { currentAge = calculateAge(newdate, currentAge); }}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.