0

I'm trying to make a pattern-matching using HTML5 constraint-validation to check if a value is not equal to a given value.

<select pattern="(?!ZZZ)">
    <option value="ZZZ">Please select a nation™</option>
    ...
    <option value="GER">Germany (GER)</option>
    ...
    <option value="ZIM">Zimbabwe (ZIM)</option>
</select>

In case the user has selected the default value ZZZ it should match and show the error-message (which is done via JavaScript).

I tried different online tools to check whatever pattern I use but nothing.

I simply need to check if the value does not match a constant string ZZZ but I don't get it.

Already tried to go the other way around so it has to match ZZZ and invert this regex somehow. But even there I get stuck.

KingKerosin
  • 3,639
  • 4
  • 38
  • 77

1 Answers1

2

You're overthinking it. :-) Just make the value of that option "" and use required:

select:invalid {
  color: red;
}
<form>
  <select required>
    <option value="">Please select a nation™</option>
    <option value="GER">Germany (GER)</option>
    <option value="ZIM">Zimbabwe (ZIM)</option>
  </select>
</form>

From the WHAT-WG HTML spec for required:

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, and that option element's parent node is the select element (and not an optgroup element), then that option is the select element's placeholder label option.

And so selecting that option does not make the select valid.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I've also thought about this but needed the value `ZZZ` for later use so I swapped to use `pattern`. But as @revo pointed out `select` does ignore this attribute so I have to change it otherways – KingKerosin Feb 07 '18 at 11:28
  • @KingKerosin: I assume you mean later use in JavaScript code. If so, you could always do this to get the select's value: `var value = theSelect.value || "ZZZ";` since `""` is falsy but no other string is. :-) – T.J. Crowder Feb 07 '18 at 11:31
  • 1
    Yes, later in javascript, as there will be a select from a list of nation-objects I need to find the selected one by the value and pass this nation away. But, as you already stated, this one I was overthinking and not checking the docs correctly ;) – KingKerosin Feb 07 '18 at 11:32