Form input validation using pure CSS

Is it possible to apply CSS classes based on an HTML element property (not based on an element attribute) without using JavaScript?

For example, consider the below input element:

<input type="text" id="txtName" class="form-field__input" name="txtName" value="">

      

When the user interacts with the above element and enters some text, its "value" property is updated; but the "value" attribute remains empty. Is there any means to access the element in CSS? I know it is possible to update the "value" attribute using JavaScript and then use attribute selectors to update the styles; but is there a way to achieve this using a CSS selector?

To clarify, I don't care if the input is valid or not, I just want to check if the content is available, and if the content is present then "any-css-rule-1" should apply, otherwise "any-css-rule-2".

+3


source to share


1 answer


You can use pattern

and required

attributes html

; :valid

, :invalid

pseudo classes in css

to match specific user input.



:valid + [for="txtName"]:after {
  content: "valid input";
  color: green;
}

:invalid + [for="txtName"]:after {
  content: "invalid input";
  color: red;
}
      

<!-- match exact user input "abc" -->
<input type="text" 
       id="txtName" 
       class="form-field__input" 
       name="txtName" 
       value="" 
       pattern="abc" 
       required />
<label for="txtName"></label>
      

Run codeHide result


0


source







All Articles