Home > OS >  Purpose and limitations of HTML `pattern` & `type` attributes
Purpose and limitations of HTML `pattern` & `type` attributes

Time:11-05

I'm concerning about the consistency and responsibility of two HTML attributes related to forms:

  • pattern: specifies a regular expression to match
  • type: specifies the type of control to render

I think that the use of these two attributes can be redundant and sometimes even lead to inconsistencies.

Here is an example with redundancy:

<input
      type="email"
      pattern=". @. " />

Here is an example with inconsistencies (because a value could not be both an email, and have 3 alphabetical characters):

<input
      type="email"
      pattern="[A-Za-z]{3}" />

How would you interpret this? Am I missing something?

My interpretation may not be correct (or maybe one of these attributes is too much and could be removed from the HTML). Thank you for your insights.

CodePudding user response:

Am I missing something?

Yes: the pattern="" attribute can be used with <input type="email"> to place additional restrictions on whatever e-mail address is provided by the user.

For example, supposing Google's GMail's settings pages have an <input type="email"> to allow users to specify another Gmail user for mailbox delegation or send them an internal GMail exclusive birthday e-card or something equally silly - in which case they'd use a pattern="" that only accepts known Google-owned GMail domain-names, i.e.:

<input type="email" pattern=".*?@gmail\.(com|de|co\.uk)$" title="Google-owned Gmail domain-names only." />

BTW, the HTML specs recommend that whenever pattern="" is used, that title="" is also supplied which explains the restrictions to the end-user:

When a control has a pattern attribute, the title attribute, if used, must describe the pattern. Additional information could also be included, so long as it assists the user in filling in the control. Otherwise, assistive technology would be impaired.

  • Related