manish thakur
manish thakur

Reputation: 820

How to validate react select

I am using react-select for better look on UI, and I have implemented it, Now what I am trying to do is

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

Upvotes: 6

Views: 15790

Answers (2)

Prashant Khamitkar
Prashant Khamitkar

Reputation: 1

    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

Upvotes: 0

Sreevardhan Reddy
Sreevardhan Reddy

Reputation: 731

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

Upvotes: 4

Related Questions