How to validate react select
Asked Answered
P

2

6

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.

Podgy answered 9/12, 2020 at 5:29 Comment(3)
check Controller in react hook form react-hook-form.com/get-started#IntegratingwithUIlibrariesEmbody
you can use code block for code section to make your question goodRobespierre
@SreevardhanReddy I already checked and implemented that also, but issue is it is not taking default value.Podgy
E
4

Here is the link for codesandbox, you can either wrap the component in the Controller or use setValue to manually set values and validate

https://codesandbox.io/s/bitter-wave-w1cpi?file=/src/App.js:2084-2802

https://w1cpi.csb.app/

reference https://react-hook-form.com/get-started#IntegratingwithUIlibraries

Embody answered 9/12, 2020 at 6:57 Comment(3)
hey here it is not taking default value or value as I want to show the first one as selectedPodgy
I tried with set values there it is not showing the values on submitPodgy
@manishthakur Set value is not working because it is triggered before your field is registered. Try using setTimeoutMccomb
E
0
    import React from "react";
    import {
      Button,
      Col,
      FormFeedback,
      FormGroup,
      Label,
      Modal,
      ModalFooter,
      Row,
    } from "reactstrap";
    import Select from "react-select";
    import * as Yup from "yup";
    import { Field, Form, Formik } from "formik";
    
    const Modal = ({ modal, toggle }) => {
      const checkboxes = [
        "Printer/Scanner",
        "Company Share Folder",
        "Distribution Group",
        "Security Group",
        "Email Account",
        "PC Login",
        "IT Software Support",
        "Microsoft License",
        "On-line Meeting Software",
        "OneDrive",
        "Shared Mailboxes",
      ];
    
      const initialValues = {
        selectedContact: null,
        checkboxes: checkboxes.reduce(
          (acc, checkbox) => ({ ...acc, [checkbox]: false }),
          {}
        ),
      };
    
      const validationSchema = Yup.object().shape({
        selectedContact: Yup.object().required("Contact is required"),
      });
    
      const handleSubmit = (values) => {
        console.log(values);
        toggle();
      };
    
      const customStyles = {
        menu: (provided) => ({
          ...provided,
          zIndex: 9999,
        }),
        menuPortal: (base) => ({
          ...base,
          zIndex: 9999,
        }),
      };
    
      const contacts = [
        { value: "1", label: "Prashant Khamitkar" },
        { value: "2", label: "Abhishek Jadhav" },
        { value: "3", label: "Rakesh Reddy" },
        { value: "4", label: "Nitin Yadav" },
        { value: "5", label: "Ashwani Kumar" },
      ];
    
      return (
        <Modal size="lg" isOpen={modal} toggle={toggle} centered>
          <div className="modal-header">
            <h5 className="modal-title mt-0" id="myLargeModalLabel">
              Offboarding
            </h5>
            <button
              onClick={toggle}
              type="button"
              className="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div className="modal-body">
            <Formik
              initialValues={initialValues}
              validationSchema={validationSchema}
              onSubmit={handleSubmit}
              enableReinitialize
            >
              {({ setFieldValue, errors, touched }) => (
                <Form>
                  <FormGroup>
                    <Row>
                      <Col md={12}>
                        <Row className="mt-3 mb-0 mb-lg-5">
                          <Col lg="8">
                            <Label
                              style={{
                                position: "relative",
                                display: "inline-block",
                              }}
                            >
                              CONTACT
                              <i
                                className="fas fa-asterisk"
                                style={{
                                  color: "red",
                                  fontSize: "0.5em",
                                  position: "absolute",
                                  top: "0.5em",
                                  right: "-1.5em",
                                }}
                              ></i>
                            </Label>
                            <Field name="selectedContact">
                              {({ field, form }) => (
                                <Select
                                  options={contacts}
                                  onChange={(option) =>
                                    form.setFieldValue(field.name, option)
                                  }
                                  value={field.value}
                                  menuPortalTarget={document.body}
                                  styles={customStyles}
                                  placeholder="Select Contact"
                                  classNamePrefix="select2-selection"
                                  menuPlacement="auto"
                                />
                              )}
                            </Field>
                            {touched.selectedContact && errors.selectedContact && (
                              <FormFeedback
                                type="invalid"
                                style={{ display: "block" }}
                              >
                                {errors.selectedContact}
                              </FormFeedback>
                            )}
                          </Col>
                        </Row>
                        <Row className="mt-3 mb-0 mb-lg-5">
                          <Col lg="12">
                            <Label>DISABLE</Label>
                            <Row>
                              {checkboxes.map((item, index) => (
                                <Col key={index} lg="4" md="6" sm="12">
                                  <div className="form-check">
                                    <Field
                                      className="form-check-input"
                                      type="checkbox"
                                      id={item}
                                      name={`checkboxes.${item}`}
                                    />
                                    <Label htmlFor={item}>{item}</Label>
                                  </div>
                                </Col>
                              ))}
                            </Row>
                          </Col>
                        </Row>
                      </Col>
                    </Row>
                  </FormGroup>
                  <ModalFooter>
                    <Button color="info" type="submit">
                      CREATE TICKET
                    </Button>
                    <Button color="secondary" onClick={toggle}>
                      CANCEL
                    </Button>
                  </ModalFooter>
                </Form>
              )}
            </Formik>
          </div>
        </Modal>
      );
    };
    
    export default Modal;
Look this is my sample modal component inside this i have kept the validation of the select contact dropdown using formik+yup
Esoterica answered 29/7 at 23:2 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Exegete

© 2022 - 2024 — McMap. All rights reserved.