'Material UI DatePicker set to Required
i am using the Material UI DatePicker in my react app and need to set the date to be required?
Do I need to create a custom validator checking value on submit or is there a prop I can use to set field to required?
<DatePicker
spacing={2}
PopoverProps={{ container: this.props.container }}
onChange={this.updateEndDate}
value={this.state.endDate}
initialFocusedDate={this.state.startDate}
minDate={this.state.startDate}
disablePast="true"
disableToolbar="true"
variant="inline"
label="End Date"
// I have tried adding required, required="true", required={true}
/>
Solution 1:[1]
There is no required
attribute/prop on the material-ui/date-picker. What can be done is to set a default date say today. And handle the error/required criteria onChange
.
Solution 2:[2]
Given that the value of the input is monitored using endDate
, set helperText
and error
to update the UI for the input in an error condition.
const requiredError = endDate === '' || endDate === undefined
const helperText = requiredError ? 'Input is required' : undefined
<DatePicker
... // other attributes
helperText={helperText} // this is almost right
error={requiredError}
/>
But, if you specify helperText
or error
, then you will override other date format checking error messages that the input will display, so you can do it this way:
const errorProps = requiredError ? {
helperText: 'Input is required',
error: true
} : { }
<DatePicker
... // other attributes
// Preserve date format checking
// Provide force error properties only if failing required test
{ ...errorProps }
/>
Note, using the KeyboardDatePicker
from @material-ui/pickers v 3.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Y M |
Solution 2 | Zak Patterson |