This tutorial aims to provide an understanding of Pattern Testing techniques and their implementation in HTML.
By the end of this tutorial, you will be able to identify and test repeating patterns within a system using various Pattern Testing techniques.
You should have a basic understanding of HTML and web development concepts.
Pattern Testing, also known as Pattern Matching, is the process of checking a given sequence of tokens for the presence of the constituents of some pattern.
One common way of pattern testing in HTML is using Regular Expressions. Regular expressions are sequences of characters that form a search pattern. This pattern can be used to match, locate, and manage text.
Here's an example of a simple regular expression:
/^Hello World$/
In this example, ^
asserts start of a line, Hello World
is the pattern to match, and $
asserts end of a line.
HTML5 introduced the pattern
attribute for the input element. The pattern attribute works with text-based input types: text, search, url, tel, email, and password.
Here's an example:
<input type="text" id="username" pattern="[a-zA-Z0-9]{5,12}" title="Username should only contain letters and numbers and be 5-12 characters long.">
In this example, the pattern attribute is used to enforce specific rules for the input field.
<script>
var str = "Hello World!";
var patt = new RegExp("^Hello World$");
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
</script>
In this example, we are testing if the string "Hello World!" matches the pattern "^Hello World$". The result (true or false) is displayed in an element with id="demo".
<form>
<input type="text" name="username" pattern="[a-zA-Z]{3,}" title="Three or more letters">
<input type="submit">
</form>
In this example, the pattern attribute is used to require that an input field must have more than 2 letters.
In this tutorial, we learned about Pattern Testing techniques and how to implement them in HTML. We discussed regular expressions and the pattern attribute in HTML5.
<script>
var str = "test@example.com";
var patt = new RegExp("^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$");
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
</script>
In this example, we are testing if the string "test@example.com" matches the pattern of an email address.
<form>
<input type="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">
<input type="submit">
</form>
In this example, the pattern attribute is used to enforce specific rules for the password field.