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

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}
/>
)}
/>

Related

DatePicker using React Hook Form not displaying format correctly

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

next js state change doesnt change value of input

I have this piece of code but that does not change value of input field when state changes.State changes when user clicks on a row. State is changing as i printed the value outside text field but that does not reflect in input field. I tried with value instead of defaultValue but it doesnt work.
<Controller
name="name"
control={control}
defaultValue={selectedRow.name}
value={selectedRow.name}
rules={{
required: true,
}}
render={({ field }) => (
<TextField
variant="outlined"
fullWidth
id="name"
label="Name"
error={Boolean(errors.name)}
helperText={
errors.name ? 'Name is required' : ''
}
{...field}
></TextField>
)}
></Controller>
It looks like you use react-hook-from (https://react-hook-form.com/).
value and onChange should be inside of TextField like this.
<Controller
name="name"
control={control}
rules={{
required: true,
}}
render={({ field, value, onChange }) => (
<TextField
value={value}
onChange={onChange}
variant="outlined"
fullWidth
id="name"
label="Name"
error={Boolean(errors.name)}
helperText={
errors.name ? 'Name is required' : ''
}
{...field}>
</TextField>
)}
/>

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>}

react-hook-form, error when using for data update

I am trying to configure a react-hook-form to work for create and update operations. I am using material ui autocomplete and textfield.
The problem I am facing is with a field that has autocomplete.
If I pass an input value, it displays it, but when the form is submitted, the required error is triggered (as if the field has not been filled in).
This is my code:
<Controller
control={control}
name="type"
render={({ field: { onChange, value }, fieldState: { error } }) => (
<Autocomplete
value={value}
onChange={(event, item) => {
onChange(item.value);
}}
id="type"
defaultValue={props.operation === 'edit' ? props.values.type : null}
options={projectTypes}
renderInput={(params) => <TextField {...params}
error={!!error}
helperText={error ? error.message : null}
label="type"
{...register('type')}
/>}
/>
)}
rules={{ required: 'Project type is required' }}
/>
I have tried to add the input value as "inputValue", but then my options, are not available and I cannot either clear the value from the field.
Any ideas on what is wrong here?
The problem is you're using both <Controller /> and register to register your field.
You should only use one of them, in your use case you should use <Controller /> and get rid of the register call inside your <TextField />.
You should also pass the defaultValue for your field to <Controller /> instead of passing it to <Autocomplete />.
<Controller
control={control}
name="type"
defaultValue={props.operation === 'edit' ? props.values.type : null}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<Autocomplete
value={value}
onChange={(event, item) => {
onChange(item.value);
}}
id="type"
options={projectTypes}
renderInput={(params) => (
<TextField
{...params}
error={!!error}
helperText={error ? error.message : null}
label="type"
/>
)}
/>
)}
rules={{ required: 'Project type is required' }}
/>

setValue in react hook form not working with react-datepicker

While i setting value dynamically to react-datepicker throwing an error "RangeError: Invalid time value"
This is my datepciker code
<Controller
control={control}
className="form-control"
name="from_date"
render={({ field }) => (
<DatePicker
onChange={(e) => field.onChange(e)}
selected={field.value}
dateFormat="dd-MM-yyyy"
minDate={new Date()}
/>
)}
{...register("from_date", { required: true })}/>
This is how i setting value to datepicker
var mydate = moment(date_from_db, 'DD-MM-YYYY').format("DD-MM-YYYY");
setValue('date_field', mydate)
Can anyone explain whats wrong with my code?
Try doing
<Controller
control={control}
className="form-control"
name="from_date"
render={({ field }) => (
<DatePicker
onChange={(e) => field.onChange(e)}
selected={field.value}
dateFormat="dd-MM-yyyy"
minDate={new Date()}
/>
)}
{...register("from_date", { required: true })}/>
var mydate = moment(date_from_db).format("DD-MM-YYYY");
setValue('from_date', mydate)

Resources