parti
parti

Reputation: 215

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>

Upvotes: 0

Views: 259

Answers (1)

curveball
curveball

Reputation: 4505

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.

Upvotes: 1

Related Questions