skip to Main Content

When validation fails, I want the error message and TextField to look this way:
Desired result image.

So far, using MUI, I’m getting close to the desired result. Here is where I’m at: My progress image, but I’m not sure how to show the red border only if there is validation error.

In addition to that, I feel like I’m doing a lot custom style to make this look that way.

sx={{
              fontSize: 20,
              color: 'black',
            }}

Maybe I’m doing something wrong. So please let know how I can improve it.

Here is my code: https://codesandbox.io/s/naughty-pond-5fg5z9?file=/src/App.js

2

Answers


  1. Chosen as BEST ANSWER

    Another solution I found for this was:

    Another solution I found was this: 
    sx={{
                '&.MuiFormControl-root:has(.Mui-error)': {
                  // if a child of FormControl has class Mui-error apply css to FormControl
                  borderLeft: '3px solid red',
                },
              }}
    

  2. In order to to show the red border only if there is validation error change this code:

    <FormControl
      sx={{
        "&.MuiFormControl-root": {
          borderLeft: "3px solid red"
        }
      }}
    

    To this:

    <FormControl
      sx={formik.touched.ssn && formik.errors.ssn !== undefined && {
        "&.MuiFormControl-root": {
          borderLeft: "3px solid red"
        }
      }}
    

    Basically you should conditionally apply style which adds red border.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search