1

Ideally, I would like the label text to change color when the input value is invalid.

Example:

<form>
  <label>
    Enter an email address:
    <input type="email">
  </label>
</form>

Ideally, I would use something like this, but it does not work because it is the <input> that's invalid, not the <label>:

label:invalid {
  color: red
}

I have my <label> and <input> set up this way so that I don't need to pass in id's into these elements.

Similar to this, however the <label> and <input> are not siblings: https://pretagteam.com/question/change-the-colour-of-a-label-when-an-input-is-invalid

Josh
  • 2,232
  • 3
  • 15
  • 33
  • Does this answer your question? [How to style the parent label of a checked radio input](https://stackoverflow.com/questions/45338238/how-to-style-the-parent-label-of-a-checked-radio-input) – Ouroborus Nov 17 '21 at 20:38
  • I suppose it does answer the question, but I was hoping to avoid using JS. "Without JavaScript things get difficult". I may just have to rearchitect my form components. Thanks. – Josh Nov 17 '21 at 23:00
  • A ` – Flimm Jul 07 '23 at 21:50
  • @Flimm, okay I will vote to reopen, as its possible that some day a pure css solution might exist. But I am afraid that we might get too many rubbish answers. – Rohit Gupta Jul 09 '23 at 05:25
  • @RohitGupta My comment was originally posted on this question: https://stackoverflow.com/q/76640575/247696 and I'm pretty sure I mentioned the jQuery part of the question. I'm confused on how it ended up here, seemingly edited. – Flimm Jul 09 '23 at 13:03

1 Answers1

-1

You can solve this by referencing the label element with the variable name label and manipulating its property at your preferences.

let label = document.querySeletor("label")
 
if (!isValid(email){
   label.style.Color = "red"
}

However, you could create a function that checks for input validation e.g function isValid(email) that consist of regex

Does the aforementioned answer your question?