0

I have a form, with a label and input type=text. I am using the pattern="" to validate the text and am displaying a message under the text input when the validation fails. I want to be able to change the color of the label as well as the text inside the text input, but cant seem to get it going. This is what I have so far. I do not want to use js.

               <div class="form-group address">
                <label for="address" class="form-group__names" id="invalid">Address</label>
                <input type="text" name="address" pattern="^\d+\s[A-z]+\s[A-z]+,\s+[A-z]+,\s+[A-z] 
                {2}\s+\d{5}" />
                <b></b>
              </div>

            .form-group input:invalid + b:before {
             content: "Form is invalid";
             color: red;
            }

             input[type="text"]:invalid + label#invalid {
             color: red;
            }
Mike0809
  • 41
  • 1
  • 11
  • Try `input[type="text"]:invalid ~ label`, but it will select no previous siblings... maybe change the order of elements? – skobaljic Sep 19 '19 at 18:36
  • That works if the Address element follows the input field, but I need the Address label on top, – Mike0809 Sep 19 '19 at 18:44
  • You can do it via css only if you reorder items [this way](https://jsfiddle.net/2hu6qz0f/2/) or similar. – skobaljic Sep 20 '19 at 06:51

1 Answers1

1

CSS has general sibling combinator ~ and adjacent sibling combinator + and non of them can select previous sibling element. Therefor you gotta change the order of your elements, so the input comes first. This is one way to do it:

.form-group input:invalid+b:before {
  content: "Form is invalid";
  color: red;
}

input[type="text"]:invalid~label {
  color: red;
}

.address {
  position: relative;
  padding-left: 100px;
}

.address label {
  position: absolute;
  left: 0;
  line-height: 30px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="form-group address">
    <input type="text" id="address" name="address" pattern="^\d+\s[A-z]+\s[A-z]+,\s+[A-z]+,\s+[A-z]{2}\s+\d{5}" />
    <b></b>
    <label for="address" class="form-group__names" id="invalid">Address</label>
  </div>
</div>

Also on JSFiddle

skobaljic
  • 9,379
  • 1
  • 25
  • 51
  • How to implement it if the label above input? – HackerMF Oct 04 '22 at 17:47
  • There is no wide browser support to somewhat *previous sibling selector*, I suggest you read [this post](https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector). – skobaljic Oct 20 '22 at 08:50