I am trying to use Formik with React to crete a form. However, I am having a problem displaying a Drop Down list with errors if nothing is selected i.e., Both the Input and Select fields are mandatory.
So Firstly I have created a custom Input and Select component where props like classNames
and Invalid
are passed.
Custom Input [OnClick and ntohing entered, turn the border red and validation error = true]
Custom Input
export interface IInputProps extends InputProps{
children?: ReactNode,
className?:string
}
export default ({className, ...props}: IInputProps) => {
if(props.invalid)
className += ' is-invalid'
return(
<Input className={className} {...props} />
)
}
Custom Select [OnClick and ntohing selected, turn the border red and validation error = true]
import Select from "react-select"
import { StateManagerProps } from "react-select/dist/declarations/src/useStateManager";
export interface IStateManagerProps extends StateManagerProps{
children?: ReactNode,
className?:string
invalid?:boolean
}
export default ({className, ...props}: IStateManagerProps ) => {
if(props.invalid)
className += ' is-invalid'
return(
<Select className={className} {...props} />
)
}
CSS
.form-control.is-invalid {
border-color: $danger !important;
}
.border-bottom{
border-color: transparent !important;
border-bottom: 2px solid red !important;
}
Main Form.
export function Validation() {
return useFormik({
enableReinitialize: true,
initialValues: {
name: "" ,
country:""
},
validationSchema: validationSchema(),
onSubmit: (values) => {
}
});
}
export function validationSchema() {
return Yup.object({
name: Yup.string().required("Name field is required"),
country: Yup.string().required("Country field is required"),
});
}
obj = [
{
"id":"qwerc",
"code":"1",
"label":"USA",
"name":"USA"
},
{
"id":"fdf3a96bda",
"code":"CXGD",
"label":"AUS"
"name":"AUS"
}
]
const MainForm = (validation) => {
return
(
<Form>
<Input
className="form-control border-bottom"
onChange={onChange}
value={validation.values?.name || ""}
name="name"
type="text"
placeholder="Enter name"
onBlur={validation.handleBlur}
invalid={validation.touched.name && validation.errors.name? true: false}
/>
{ validation.touched.commodityType && validation.errors.commodityType? (
<FormFeedback type="invalid"> {validation.errors.name}</FormFeedback>
) : null}
//import Select from './custom/Select'
<Select
options={obj}
className="form-control border-bottom"
onChange={() => onChange}
value={validation.values?.country|| ""}
name="country"
type="select"
placeholder="Country"
onBlur={validation.handleBlur}
invalid={validation.touched.country && validation.errors.country? true: false}
/>
{ validation.touched.country && validation.errors.country? (
<FormFeedback type="invalid"> {validation.errors.country}</FormFeedback>
) : null}
</Form>