How to use the Pattern attribute?

Asked

Viewed 10,046 times

2

I’ve been all over the Internet, even W3school, and all I see is them reporting the "ready" code. With keys, interrogations, bars, cipher and several other parameters.

But I couldn’t find anything explaining how to use these parameters, what they’re for?

  • 3

    W3school is definitely not one of the places I would recommend to study. It is a site that became famous for the lack of quality information (and if it was a good thing, you did not need to try to misappropriate the name W3, which has no relation to them). That said, what you have to search for is Javascript’s Regex, (regular expressions), which is the default used in validation by pattern. See the MDN link on https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-Pattern

  • 1

    More specifically, the Regex syntax used is here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

1 answer

5


The attribute pattern in forms in HTML 5 allow that form to be validated through a Regular Expression.

Regular expressions are a way to validate textual expressions that follow some type of pattern and when applying this expression within the parameter pattern HTML will ensure that this standard is met.

Example:

You have a form that needs to get a license plate from a car. This type of information in Brazil follows a certain pattern: 3 letters from A to Z, followed by a dash and finally 4 numbers from 0 to 9. It is possible to express this in the following form:

<form action="#">
  <label for="placa">Placa: </label>
  <input type="text" name="website" pattern="[A-Za-z]{3}-[0-9]{4}">
  <input type="submit">
</form>

Before using the attribute pattern needs an understanding of how to work with regular expressions. Below are some articles that can help you:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.