Anjayluh
Anjayluh

Reputation: 1786

How to hide error message and only highlight field in yup test

I have a schema running a number of validations. But I don't want to display some error messages in case of an error although I want the field to be highlighted. Giving an empty string instead of an error message results in formik not showing the red input field yet the validation runs. Here is my current code

const LocationDetailsSchema = Yup.object().shape({
  location: Yup.string(),
  locationCategory: Yup.string(),
  lat: Yup.number()
    .min(-85, "Not a valid Latitude")
    .max(85, "Not a valid Latitude")
    .nullable()
    .transform(function(value) {
      return this.isType(value) ? value : null;
    })
    .test(
      "match",
      "", //empty string fails, putting a text shows but i don't want the text to appear
      function(){
        if (principalAmount>=500000) return true;
        return false;
      }
    ),
  lon: Yup.number()
    .min(-180, "Not a valid Longitude")
    .max(180, "Not a valid Longitude")
    .nullable()
    .transform(function(value) {
      return this.isType(value) ? value : null;
    })
    .test(
      "match",
      "Is valid", // this works but i don't want the text to appear either
      function(){
        if (principalAmount>=500000) return true;
        return false;
      }
    ),
});

Upvotes: 3

Views: 4737

Answers (1)

Mehdi Faraji
Mehdi Faraji

Reputation: 3846

You may want to use the formik this way so you have access to the fields errors if they have any :

 <Formik
        initialValues={initialValues}
        onSubmit={onSubmit}
        validationSchema={validationSchema}
      >
        {(props) => {
          return (
            <Form>
              <Input
                style={{
                  direction: "rtl",
                  border:
                    props.touched.name && props.errors.name ? "red" : "none",
                }}
                onBlur={() => props.setFieldTouched("name")}
                onChange={(e) => props.setFieldValue("name", e.target.value)}
                props={props}
                className={""}
              />
            </Form>
          );
        }}
      </Formik>

Here I apply border style to the component if it is touched and has errors :

 border : props.touched.name && props.errors.name ? "red" : "none",

You can have your own logic and styles applied by using this method .

Upvotes: 1

Related Questions