KeyboardDateTimePicker Material UI Not null validation - reactjs

I have implemented KeyboardDateTimePicker. I am not able to validate it for empty or null values? I tried few things for validation, yet its not working.
Code:
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDateTimePicker
required={true}
format="dd/MM/yyyy HH:mm"
value={this.props.StartDate}
placeholder="dd/mm/yyyy hh:mm"
onChange={(event) => this.props.handleDateTime(event)}
/>
</MuiPickersUtilsProvider>
I tried placing required, validated=true in form control, yet its not working.
Did not find any keywords here :
https://material-ui-pickers.dev/api/KeyboardDatePicker
About DateTimePicker:
https://material-ui-pickers.dev/demo/datetime-picker
If anyone has faced similar issue please suggest.

Add props error and helperText
You can make a function checkErrors=()=>this.props.StartDate?false:true and use props
error={checkErrors()}
helperText={checkErrors():"Some error message":""}
Your code may looking something like this:
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDateTimePicker
required={true}
format="dd/MM/yyyy HH:mm"
value={this.props.StartDate
}
placeholder="dd/mm/yyyy hh:mm"
onChange={(event) => this.props.handleDateTime(event)}
error={this.props.StartDate?false:true}
helperText={this.props.StartDate?"Some error message":""}
/>
</MuiPickersUtilsProvider>

Related

MUI DatePicker + date-fns localization problem

The problem occours when I'm using MUI DatePicker with LocalizationProvider and AdapterDateFns with Hungarian local.
<LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={hu}>
<DesktopDatePicker
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => (
<TextField
{...params}
inputProps={{
...params.inputProps,
placeholder: "yyyy. MM. dd."
}}
/>
)}
/>
</LocalizationProvider>
All latest dependencies.
The problem is when I'm trying to type in the date manually the curzor jumps around wierd in the month and day part. The LocalizationProvider transforms the input mask to "yyyy. MM. dd." and that is what I want to have, but it seems like the curzor doesn't adapt to the new format and bugs out.
You can try it here:
CodeSandbox
Is there any way to fix this or work around it?
NOTE: The cause seems to be the date-fns. It works fine with dayjs, but I have to use date-fns, so I have to make that work somehow.

How to remove of MUI 5 TextField label without having notched style?

I'm working on replacing the DatePicker component in our app with the new #mui DatePicker, and I'm having some trouble getting the TextField to render without the floating label and the notched input style. Here is my latest attempt:
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
onError={(reason, value) => console.log(reason, value)}
disableOpenPicker
className={styles.datepicker}
disableMaskedInput
onChange={() => undefined}
onAccept={handleAccept}
open={datePickerVisible}
value={getSafeDate(value) as Date}
onClose={partial(handleDatepickerVisibilityChange, false)}
{...datepickerProps}
renderInput={(params) => (
<TextField
id={id}
{...inputProps}
{...params}
onChange={handleInputChange}
error={errorText !== null}
helperText={errorText}
onBlur={handleValueChange}
onKeyPress={handleKeyPress}
hiddenLabel
size='small'
fullWidth
/>
)}
/>
</LocalizationProvider>
I've tried many different combinations for TextField props, such as adding InputLabelProps={{shrink:false}}, InputLabelProps={{shrink:true}}, and inputProps={{notched:false}} but always end up looking like this:
Does anyone have an idea of how to correct this, or if it's possible?
Thanks!
The issue was fixed in release v5.4.0
​[TextField] Remove notch when no label is added (#30560) #alisasanib
Updating to v5.4.0 should solve the issue.

Having an issue with antd datepicker not displaying value

Im having an issue with the datepicker component. I have tried multiple things but the date I am passing will not display in the datepicker. I just set the fields in the beginning of my component. The warrantynotes field shows just fine. I get different errors depending on what I try but mostly :
TypeError: date.clone is not a function
format
form.setFieldsValue({
datepurchased: e.datepurchased,
warrantynotes: e.warrantynotes,
})
<Form.Item
name={'datepurchased'}
label="Date Purchased:"
// defaultValue={moment(warranty.datepurchased)}
// format={dateFormat}
// defaultPickerValue={moment(warranty.datepurchased)}
>
<DatePicker
onChange={handleChange}
// defaultValue={moment(warranty.datepurchased)}
// format={dateFormat}
// defaultPickerValue={moment(warranty.datepurchased)}
></DatePicker>
</Form.Item>
I tried to change your code, use defaultValue instead defaultPickerValue
const { DatePicker, Space } = antd;
function handleChange() {}
const myDate = "2021-01-07";
ReactDOM.render(
<Space direction="vertical" size={12}>
<DatePicker onChange={handleChange} defaultPickerValue={moment()} />
<DatePicker onChange={handleChange} defaultValue={moment()} />
<DatePicker onChange={handleChange} defaultValue={moment(myDate)} />
</Space>,
mountNode
);

React-Final-Form delays in taking input with render props in Field

I am currently working on a react project. I am using react-final-form for fetching the data in the form. As I am using the material UI component to create the form I am creating the form somewhat like this.
Code
<Form
onSubmit={onSubmit}
validate={validate}
render={({ handleSubmit, values }) => (
<form onSubmit={handleSubmit}>
<FormControl variant="outlined" className={classes.formControl} key={fieldKey}>
<Field
name={field.fieldName}
render={({ input }) => (
<TextField
{...input}
className={classes.textField}
variant="outlined"
label={props.field.label}
placeholder={props.field.description}
required={props.field.isMandatory}
InputLabelProps={{
shrink: true,
}}
/>
)}
type="text"
/>
</FormControl>
</form>
)}
/>
Now as soon as I remove the input props from the render props it is working fine. but with the input props, it delays in taking input. Without input props, I could not fetch the value from the form.
Is there any way to resolve this time delay?
Thanks in advance.
If you want a simple field. Maybe you can pass on only essential props.
<TextField
name={input.name}
value={input.value}
onChange={input.onChange}
/>
The solution to this is subscriptions.
The form is initially rendered on every action, react-final-form allows to handle subscription,
<Form subscription={{handeleSubmit: true}} ...> </Form>
We can do somewhat like this
There is a video link for this. Video
Hope you find this helpful 😉

How to make autocomplete field of material UI required?

I have tried a couple of ways in order to make the material UI's autocomplete field of type required but I am not getting the behavior that I wanted. I had encapsulated my field inside react hook form <Controller/> yet no luck. I want to trigger message 'Field is mandatory' on submit when nothing is added to the field.
Below is the code snippet, I have not removed comments so that it becomes a bit easier for others to understand the approach that I had followed earlier -
<Controller
name="displayName"
as={
<Autocomplete
value={lists}
multiple
fullWidth
size="small"
limitTags={1}
id="multiple-limit-lists"
options={moduleList}
getOptionLabel={(option) => option.displayName}
renderInput={(params,props) => {
return (
<div>
<div className="container">
<TextValidator {...params} variant="outlined" label="Display Name*" className="Display Text"
name="displayName" id="outlined-multiline-static"
placeholder="Enter Display-Name" size="small"
onChange={handleDisplay}
// validators={['required']} this and below line does throw a validation but the problem is this validation stays on the screen when user selects something in the autocomplete field which is wrong.
// errorMessages={['This field is required']}
// withRequiredValidator
/>
</div>
</div>
)
}}
/>
}
// onChange={handleDisplay}
control={control}
rules={{ required: true }}
// required
// defaultValue={options[0]}
/>
<ErrorMessage errors={errors} name="displayName" message="This is required" />
You can use the following logic to get it worked. Though this might not be the best solution but works.
<Autocomplete
renderInput={(params) => (
<TextField
{...params}
label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label
required={value.length === 0}
/>
)}
/>
I tried using the built in required in textfield for autocomplete, and it works like a charm. Maybe you can use this as a reference.
<Autocomplete
renderInput={(params) => {
<TextField {...params} required />
}
// Other codes
/>
Since you are rendering <TextValidator>, you should apply mandatory(required) attribute to that component not on <AutomComplete>.
Try this if your Material UI version is v5
<TextField
{...params}
required
label="Tags"
value={value}
InputProps={{
...params.InputProps,
required: value.length === 0,
}}
/>

Resources