I'm trying to validate a form made using form fields from React MD by using React Hook Form. The text input fields are working fine.
But the validations aren't working on the select field. Here is the code:
<Controller
control={control}
name="salutation"
defaultValue=""
rules={{ required: "Salutation is required" }}
disabled={isSubmitting}
render={(props) => (
<Select
id="salutation"
{...props}
label="Salutation"
options={SALUTATION_ITEMS}
value={salutationValue}
onChange={(e) => handleSalutationChange(e)}
disableLeftAddon={false}
rightChildren={
<RiArrowDownSFill className="dropDownArrow" />
}
/>
);
}}
/>
The error persists even after the user selects a value:
{errors.salutation && (
<div className="validation-alert msg-error ">
<p>{errors.salutation.message}</p>
</div>
)}
I'm probably missing something or doing something wrong.
I think you are missing props.value and props.onChange(e) and you may not need handleSalutationChange(e):
<Controller
control={control}
name="salutation"
defaultValue=""
rules={{ required: "Salutation is required" }}
disabled={isSubmitting}
render={(props) => (
<Select
id="salutation"
{...props}
label="Salutation"
options={SALUTATION_ITEMS}
value={props.value} // This one: props.value
onChange={(e) => {
props.onChange(e) // I think you are missing this
handleSalutationChange(e) // NOT Needed ?
}}
disableLeftAddon={false}
rightChildren={
<RiArrowDownSFill className="dropDownArrow" />
}
/>
);
}}
/>
Related
On selecting specific date in DatePicker component, getting error as 'handleChange is not a function' as mentioned above. DatePicker component is wrapped in Controller component of react-hook-form. Expected to display date on DatePicker input. How could it be resolved? See the code below:
<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="date"
render={({ handleDateChange, selectedDate, ref }) => (
<>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify="space-around">
<DatePicker
ref={ref}
value={selectedDate}
onChange={handleDateChange}
format={`d | ` + `MMMM | ` + `yyyy`}
disablePast
animateYearScrolling
margin="normal"
style={{ cursor: "pointer" }}
/>
</Grid>
</MuiPickersUtilsProvider>
<br />
</>
)}
rules={{
required: "Date is required"
}}
/>
</form>
Here is the CodeSandbox link: https://codesandbox.io/s/jolly-currying-lwtrj
Any suggestion or code changes is highly appreciated.
Firstly, there is no such properties as handleDateChange or selectedDate, perhaps this is what you mean:
render={({ onChange: handleDateChange, value: selectedDate, ref }) => (
Secondly, you're using react-hook-form v7, the render method signature of Controller was changed. See the migration guide here. You need to get the input props from the field property, not directly from the render props:
render={({ field }) => {
const {
onChange: handleDateChange,
value: selectedDate,
ref
} = field;
Full working code:
<Controller
control={control}
name="date"
render={({ field }) => {
const {
onChange: handleDateChange,
value: selectedDate,
ref
} = field;
return (
<>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify="space-around">
<DatePicker
ref={ref}
value={selectedDate}
onChange={handleDateChange}
format={`d | ` + `MMMM | ` + `yyyy`}
disablePast
animateYearScrolling
margin="normal"
style={{ cursor: "pointer" }}
/>
</Grid>
</MuiPickersUtilsProvider>
<br />
</>
);
}}
rules={{
required: "Date is required"
}}
/>
Live Demo
I'm following the docs of Antd and tried to use this piece of code from here antd dynamic form item:
import { Form, Input, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '#ant-design/icons';
const Demo = () => {
const onFinish = values => {
console.log('Received values of form:', values);
};
return (
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
<Form.List name="users">
{(fields, { add, remove }) => (
<>
{fields.map(field => (
<Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
<Form.Item
{...field}
name={[field.name, 'first']}
fieldKey={[field.fieldKey, 'first']}
rules={[{ required: true, message: 'Missing first name' }]}
>
<Input placeholder="First Name" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'last']}
fieldKey={[field.fieldKey, 'last']}
rules={[{ required: true, message: 'Missing last name' }]}
>
<Input placeholder="Last Name" />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(field.name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
Add field
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
But I have this error, when I add some rows, then delete some of them and finally submit, the validator keeps working even after I had deleted those rows.
Here is a demo that replicates my error.
https://codesandbox.io/s/quizzical-ride-m1pe6?file=/src/App.js
This is a bug from antd.
An issue was opened about that on their github.
https://github.com/ant-design/ant-design/issues/27576
And the associate PR :
https://github.com/react-component/field-form/pull/213
A fix has been merged last week. Normally, the next release will include the fix.
In Formik, I try to use {...formik.getFieldProps('email')} on my input field
instead of using value, onChange, and onBlur. But it's not working.
This works :
<input id="email" name="email" type="text" value={formik.values.email} onChange={formik.handleChange} onBlur={formik.handleBlur} />
But this doesn't :
<input id="email" type="text" {...formik.getFieldProps("email")} />
Code is here : https://codesandbox.io/s/formik-pb-with-getfieldprops-83tze?fontsize=14
Any ideas ?
Thanks !
As MiDas said, what you are doing should work if you are on latest version.
I'll mention an even more concise alternative: the Field component.
Field component handles the field property propagation for you.
Simple example:
<Field name="email" type="text" />
Notice that you don't need to do {...formik.getFieldProps("email")}, or any other "boilerplate".
Related to Field is useField, which can be used to make custom form components just as easy to use - no "boilerplate" needed.
A custom component:
function TextInputWithLabel({ label, ...props }) {
// useField() returns [formik.getFieldProps(), formik.getFieldMeta()]
// which we can spread on <input> and also replace ErrorMessage entirely.
const [field, meta] = useField(props);
return (
<>
<label
htmlFor={props.id || props.name}
css={{ backgroundColor: props.backgroundColor }}
>
{label}
</label>
<input className="text-input" {...field} type="text" {...props} />
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
) : null}
</>
);
}
Usage:
<TextInputWithLabel name="input1" label="Random comment" />
As seen in code from codesandbox.
I am trying to handle onChange for Field component in React Formik, but it doesn't work. I also tried to handle it outside Formik component by:
handleChange(e) {
console.log('changing');
}
<Field type="radio" name="players" value="1" onChange={e => this.handleChange(e)}/>
but I am getting the warning:
A component is changing an uncontrolled input of type text to be
controlled. Input elements should not switch from uncontrolled to
controlled (or vice versa).
For now my code looks like this:
<Formik
onChange={() => {
console.log('changing');
}}
onSubmit={(values) => {
console.log('submitted');
}}
>
{({ isSubmitting, handleChange }) => (
<Form>
<InputWrapper>
<span>1</span>
<Field type="radio" name="players" value="1" onChange={handleChange}/>
<span>2</span>
<Field type="radio" name="players" value="2" onChange={handleChange}/>
</InputWrapper>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Loading..' : 'Start'}
</button>
</Form>
)}
</Formik>
Any tips/ideas?
One issue I have found with introducing the onBlur:handleBlur to your Formik Field is that it overrides the Formik Validation.
Use onKeyUp={handleChange}
This solved said problem
You must to use the InputProps of Field like the following...
import { TextField } from 'formik-material-ui';
<Field
type="radio"
name="players"
value="2"
component={TextField}
InputProps={{ onBlur:handleBlur }}/>
To use the InputProps in the Field you need to use a component TextField from the formik-material-ui lib.
Another way is use the onKeyUp or onKeyDown, that functions work ok with Field and that functions are like onChange
<Field
type="radio"
name="players"
value="2"
onKeyUp =this.handleChange/>
I found one trick which worked well for me, you can use "values" of formik and call a method passing the "values" as parameter and perform the action using new values.
const handleUserChange = (userId: number) => {
//userId is the new selected userId
};
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
enableReinitialize
>
{({ isValid, isSubmitting, values }) => (
<Form>
<table className="table">
<tbody>
<tr>
<td>Users</td>
<td>
<Field name="userId" className="form-control" as="select">
<option value="">--select--</option>
{data.Users.map((user, index) => (
<option key={user.id} value={user.id}>{`User ${index + 1}`}</option>
))}
</Field>
</td>
</tr>
{handleUserChange(values.userId)}
</tbody>
</table>
<div className="row">
<div className="col-sm-12">
<SubmitButton label="Save" submitting={isSubmitting} disabled={!isValid || isSubmitting} />
</div>
</div>
</Form>
)}
</Formik>
I want to display like an error with red color unless there is a selected option.
Is there any way to do it.
For setting a required Select field with Material UI, you can do:
class SimpleSelect extends React.PureComponent {
state = {
selected: null,
hasError: false
}
handleChange(value) {
this.setState({ selected: value });
}
handleClick() {
this.setState(state => ({ hasError: !state.selected }));
}
render() {
const { classes } = this.props;
const { selected, hasError } = this.state;
return (
<form className={classes.root} autoComplete="off">
<FormControl className={classes.formControl} error={hasError}>
<InputLabel htmlFor="name">
Name
</InputLabel>
<Select
name="name"
value={selected}
onChange={event => this.handleChange(event.target.value)}
input={<Input id="name" />}
>
<MenuItem value="hai">Hai</MenuItem>
<MenuItem value="olivier">Olivier</MenuItem>
<MenuItem value="kevin">Kevin</MenuItem>
</Select>
{hasError && <FormHelperText>This is required!</FormHelperText>}
</FormControl>
<button type="button" onClick={() => this.handleClick()}>
Submit
</button>
</form>
);
}
}
Working Demo on CodeSandBox
Material UI has other types of Select(native) also where you can just use plain HTML required attribute to mark the element as required.
<FormControl className={classes.formControl} required>
<InputLabel htmlFor="name">Name</InputLabel>
<Select
native
required
value={this.state.name}
onChange={this.handleChange}
inputProps={{
name: 'name',
id: 'name'
}}
>
<option value="" />
<option value={"lala"}>lala</option>
<option value={"lolo"}>lolo</option>
</Select>
</FormControl>
P.S. https://material-ui.com/demos/selects/#native-select
The required prop only works when you wrap your elements inside a <form> element, and you used the submit event to submit the form.
this is not related to react, this is pure HTML.
In MUI v5 (2022), it works like this:
const handleSubmit = (e)=>{
e.preventDefault()
// ...
}
return (
<form onSubmit={handleSubmit}>
<Select required value={val} onChange={handleChange} required>
<MenuItem value="yes">Yes</MenuItem>
<MenuItem value="no">No</MenuItem>
</Select>
<Button type="submit">Submit</Button>
</form>
)
As you can see, it works the same way you think it should work, so what your code should probably be similar to this.
But the required prop only works when you wrap your elements inside a element, and you used the submit event to submit the form.
And if you're using <FormControl>, but the required prop on both elements:
<FormControl required>
<Select required>
// ...
</FormControl>