Html 5 Form Validation

HTML5 introduced built-in form validation capabilities that simplify client-side validation without the need for JavaScript. You can use HTML5 attributes to enforce rules for user inputs.

required: Ensures that the input field must be filled out before submitting the form.

<input type="text" name="username" required>

minlength and maxlength: Sets the minimum and maximum length of the input value.

<input type="text" name="username" minlength="3" maxlength="10" required>

pattern: Specifies a regular expression that the input value must match.

<input type="text" name="username" pattern="[A-Za-z]{3,}" required>

type: Determines the type of data expected and provides built-in validation for common types like email, number, url, etc.

<input type="text" name="username" pattern="[A-Za-z]{3,}" required>

min and max: Define the range for numerical input or date values.

<input type="number" name="age" min="18" max="99" required>
<input type="date" name="birthday" min="1900-01-01" max="2024-12-31" required>

step: Defines the step size for numerical or date inputs.

<input type="number" name="quantity" step="0.01" min="0" required>

Example Form with HTML5 Validation

Here’s an example form demonstrating several of these attributes:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5 Form Validation</title>
</head>
<body>
    <form action="/submit" method="post">
        <label for="username">Username (3-10 letters):</label>
        <input type="text" id="username" name="username" minlength="3" maxlength="10" pattern="[A-Za-z]{3,10}" required>
        <br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>

        <label for="age">Age (18-99):</label>
        <input type="number" id="age" name="age" min="18" max="99" required>
        <br><br>

        <label for="dateOfBirth">Date of Birth:</label>
        <input type="date" id="dateOfBirth" name="dateOfBirth" min="1900-01-01" max="2024-12-31" required>
        <br><br>

        <label for="quantity">Quantity (Step of 0.01):</label>
        <input type="number" id="quantity" name="quantity" step="0.01" min="0" required>
        <br><br>

        <input type="submit" value="Submit">
    </form>
</body>
</html>

How It Works

  • Required Fields: If a field marked required is left empty, the form will not submit, and the browser will prompt the user to fill it out.
  • Pattern Matching: The pattern attribute uses a regular expression to validate the input format.
  • Min/Max/Step: For numeric inputs, min, max, and step restrict the range and granularity of input values.
  • Type-Specific Validation: Input types like email, number, and date automatically validate input format.

administrator

Leave a Reply

Your email address will not be published. Required fields are marked *