Apply different styles depending on whether the field is empty or not

Viewed 38

I have a fairly simple text field (TextField) on my site. When the user enters a value into it, a site search is performed.

My question is: is it possible to apply different styles to a TextField depending on whether the field is currently empty or whether the user has entered some value.

In my case, I would like to set the bounds of the TextField to green if the field is not empty (regardless of whether the cursor is on the input field or not)

    const CssTextField = withStyles({
    root: {
      '& label.Mui-focused': {
        color: '#1062de',
      },
      '& .MuiInput-underline:after': {
        borderBottomColor: '#1062de',
      },
      '& .MuiOutlinedInput-root': {
        '& fieldset': {
          borderColor: 'black',
        },
        '&:hover fieldset': {
          borderColor: 'black',
        },
        '&.Mui-focused fieldset': {
          borderColor: '#1062de',
        },
      },
    },
  })(TextField);
2 Answers

Add the following code to your CssTextField = withStyles({})

You will also need to make sure that your CssTextField is required

  '& input:valid + fieldset': {
    borderColor: 'green',
    borderWidth: 2,
  },
  '& input:invalid + fieldset': {
    borderColor: 'red',
    borderWidth: 2,
  },
  '& input:valid:focus + fieldset': {
    borderLeftWidth: 6,
    padding: '4px !important', // override inline-style
  }

More information on mui.com:

Here's a pretty, simple and performant solution. It lies within CSS and nothing else.

HTML/JSX:

<input type="text" minlength="1" required>

CSS:

[type="text"]:valid {
border-color: red;
}

Enjoy :)

Related