I am using react-select for better look on UI, and I have implemented it, Now what I am trying to do is
- I want to validate that input field when user clicks on Done button (form submit)
- I am using react-hook-form for validation
- They provide
ref={register}
which holds the input field value - so for normal input field or select I am able to use this like below
<label htmlFor="fname">
First Name
</label>
<input
type="text"
name="fname"
id="fnameid"
className="form-control"
ref={register({
required: 'First name is required',
})}
/>
{errors.fname && (
<div>
<span className="text-danger">
{errors.fname.message}
</span>
</div>
)}
Now the above is working fine but in case of react-select
I do not know how to go forward
<Select
value={initailSelect}
onChange={(e) => onChangeAge(e)}
options={data}
/>
So here when I click on submit button it is only taking validation for fname and giving output on console for fname only
I tried doing like below
<Select
value={initailSelect}
onChange={(e) => onChangeAge(e)}
options={data}
ref={register({
required: 'age is required is required',
})}
/>
Code sandbox Here is my code sandbox My working code, Please check
Edit
I tried This approach but it is not taking up defaultValue
or Value
, as I want to show one value selected, a nd in some cases I am getting values from server Which I want to show as selected.
from How to validate react select
No comments:
Post a Comment