HTML Input Attributes
The <input> tag is a versatile HTML element used in forms to collect user inputs. Depending on the attributes set, it can accept various types of data, from text to numbers and files.
Main Attributes of the <input> Tag
| Attribute | Description |
|---|---|
type |
Specifies the type of input. |
name |
Defines the name of the input element, which is used to reference form data after submission. |
value |
Specifies the initial value of the input field. |
placeholder |
Provides a hint to the user about what kind of information is expected in the input. |
required |
Indicates that the input field must be filled out before submitting the form. |
disabled |
Disables the input field. |
pattern |
Defines a regex that the input field's value is checked against to ensure it matches a specified pattern. |
Types of <input> and Examples
| Type | Description | Example |
|---|---|---|
text |
Allows the user to enter plain text. | <input type="text" name="username" placeholder="Enter your username"> |
password |
Like text, but masks the user's input for privacy. | <input type="password" name="password" placeholder="Enter your password"> |
radio |
Allows the user to select one of a limited number of choices. | <input type="radio" name="gender" value="male" id="male"><label for="male">Male</label>
<input type="radio" name="gender" value="female" id="female"><label for="female">Female</label> |
checkbox |
Allows the user to select zero or more options from a limited number of choices. | <input type="checkbox" name="subscribe" id="subscribe"><label for="subscribe">Subscribe to newsletter</label> |
submit |
Button to submit the form. | <input type="submit" value="Submit Form"> |
email |
Includes built-in validation to check if the entered text is a valid email address. | <input type="email" name="email" placeholder="Enter your email"> |
date |
Allows the user to select a date. | <input type="date" name="dob"> |
color |
Provides a color picker to choose a color. | <input type="color" name="favoriteColor"> |
Using the pattern Attribute with Examples
The pattern attribute allows you to define a regular expression against which the input's value is checked. This is particularly useful for custom validations that go beyond the basic type checks.
Example: Validating a phone number (format: 123-456-7890):
<input type="text" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" title="Enter a phone number in the format: 123-456-7890" required>
This pattern ensures that the user enters a phone number exactly in the specified format. If the input does not match, the form will not submit, and the user will be prompted to correct the data.
Conclusion
The <input> tag is a critical element in HTML forms, providing a wide range of functionalities for gathering user inputs. Understanding how to use its various types and attributes, especially the pattern attribute for regex, can significantly enhance form handling and data validation in your web applications.