Skip to main content

Form Validation (Live Playground)

In this tutorial, we will discuss form validation in HTML5. Form validation is essential to ensure that users enter valid data before submitting the form. With HTML5, you can easily add validation to your forms using built-in attributes.

Required Attribute

The required attribute can be added to an input element to make it mandatory for the user to provide a value before submitting the form.

HTML
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required />
<input type="submit" value="Submit" />
</form>

In this example, the required attribute is added to the name input field. The form cannot be submitted until a value is provided for the name field.

Live Playground, Try it Yourself

Pattern Attribute

The pattern attribute allows you to specify a regular expression that the input value must match before the form can be submitted.

HTML
<form>
<label for="zipcode">Zip Code:</label>
<input type="text" id="zipcode" name="zipcode" pattern="\d{5}" />
<input type="submit" value="Submit" />
</form>

In this example, the pattern attribute is added to the zip code input field. The regular expression \d{5} requires the input value to consist of exactly five digits. The form cannot be submitted until the zip code value matches the pattern.

Live Playground, Try it Yourself

Min and Max Attributes

The min and max attributes can be used to set a range of valid values for numerical input types, such as number and range.

HTML
<form>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="99" />
<input type="submit" value="Submit" />
</form>

In this example, the min and max attributes are added to the age input field. The user must enter a value between 18 and 99 before the form can be submitted.

Live Playground, Try it Yourself

Input Type Validation

HTML5 also includes built-in validation for specific input types, such as email, url, and tel.

HTML
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required />
<label for="website">Website:</label>
<input type="url" id="website" name="website" required />
<input type="submit" value="Submit" />
</form>

In this example, the email and website input fields have been set to their respective input types. The browser will validate the user's input based on the expected format for these input types.

Live Playground, Try it Yourself

Conclusion

In this tutorial, we have explored form validation in HTML5. By using the built-in attributes and input types, you can easily add validation to your forms and ensure users enter valid data before submitting the form.