Form Validation
This article explains form validation.
It explains form validation in HTML.
YouTube Video
HTML Form Validation
Overview of HTML Form Validation
- HTML form validation is a mechanism to ensure that the data meets certain conditions before a user submits it. This reduces server-side errors and improves the user experience.
required
Attribute
1<form>
2 <label for="email">Email:</label>
3 <input type="email" id="email" required placeholder="Enter your email">
4 <button type="submit">Submit</button>
5</form>
- The
required
attribute specifies that input fields must be filled before submitting the form.
pattern
Attribute
1<form>
2 <label for="username">Username (letters and numbers only):</label>
3 <input type="text" id="username" name="username" pattern="[A-Za-z0-9]+" required>
4 <button type="submit">Submit</button>
5</form>
- The
pattern
attribute is used to validate whether the form input matches a specific regex pattern. For example, this checks if the username contains only alphanumeric characters.
min
and max
Attributes
1<form>
2 <label for="age">Age:</label>
3 <input type="number" id="age" name="age" min="18" max="99" placeholder="Enter your age">
4 <button type="submit">Submit</button>
5</form>
<min>
and<max>
attributes are used to specify the minimum and maximum allowable values for an input element. They are commonly used with input types likenumber
,range
, anddate
.- In this example, you can enter a number between 18 and 99.
minlength
and maxlength
Attributes
1<form>
2 <label for="username">Username:</label>
3 <input type="text" id="username" name="username" minlength="4" maxlength="12" placeholder="4-12 characters">
4 <button type="submit">Submit</button>
5</form>
- The
minlength
attribute specifies the minimum number of characters required for an input field, while themaxlength
attribute defines the maximum number of characters allowed. - In this example, you can input text between 4 and 12 characters.
The type="email"
attribute
1<form>
2 <label for="email">Email:</label>
3 <input type="email" id="email" placeholder="Enter your email">
4 <button type="submit">Submit</button>
5</form>
- The
type="email"
attribute is used to ensure that the input is in a valid email address format. This attribute provides built-in validation functionality for email address input fields.
The type="url"
attribute
1<form>
2 <label for="website">Website:</label>
3 <input type="url" id="website" name="website" placeholder="https://example.com" required>
4 <button type="submit">Submit</button>
5</form>
<input type="url">
provides an input field that requires a correct URL format. The browser automatically checks whether the input is valid as a URL.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.