parti parti - 8 months ago 106
CSS Question

Detect character in input using CSS

I'm trying to detect when an input has a double quote in it (") using ONLY CSS: When invalid, i.e. has character in it, it should then show message.
Note: The input value is dynamically placed in my editing interface.



form div#intdblquote > input[type="text"]:valid {
display: none;
position: relative}

form div#intdblquote > input[type="text"]:valid ~ .requirements {
display: none}

form div#intdblquote > input[type="text"]:invalid {
display: block}

form div#intdblquote > input[type="text"]:invalid ~ .requirements {
display: block}

<form>
<div id="intdblquote">
<input type="text" id="intdblquote" name="intdblquote" pattern="[^'\x22]+" placeholder= " " value="MyEntry"" required />
<div class="requirements">Must not contain double quote.</div>
</div>
</form>




Answer Source

Maybe I am not getting it right, but I guess everything is almost allright. You might have messed up styles and escaping. This seems to work: the warning is shown when " symbol is typed in. If you want your default value to be MyEntry" enclose the attribute in '.

form div#intdblquote > input[type="text"]:valid ~ .requirements {
  display: none;
}
  
form div#intdblquote > input[type="text"]:invalid ~ .requirements {
  display: block;
} 
<form>
  <div id="intdblquote">
   <input type="text" id="intdblquote" name="intdblquote" pattern="[^\x22]+" placeholder="" value='MyEntry"' required/>
   <div class="requirements">Required. Must not contain double quote.</div>
  </div>
</form>

The pattern attribute specifies a regular expression that the element's value is checked against. When the regexp is not satisfied, then :invalid pseudoclass takes over. Otherwise the :valid one comes into play.

Also notice that if nothing typed in :invalid pseudoclass comes into force since attribute required is present.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download