Skip to main content

Form Validation

Form Validation

Form validation is crucial for ensuring that the data entered by users is accurate and meets the required criteria. HTML5 provides built-in validation features that make it easier to validate form inputs. This guide covers basic HTML5 validation attributes and their usage.


Basic HTML5 validation

HTML5 introduces built-in form validation, allowing browsers to check the validity of form inputs before submitting. This reduces the need for JavaScript validation and enhances user experience.

<form action="/submit-form" method="post">
  <input type="text" name="username" required>
  <input type="submit" value="Submit">
</form>

Required attribute

The required attribute specifies that an input field must be filled out before submitting the form.

<form action="/submit-form" method="post">
  <input type="text" name="username" required placeholder="Enter your name">
  <input type="submit" value="Submit">
</form>

Pattern attribute

The pattern attribute specifies a regular expression that the input field's value must match in order to be valid.

<form action="/submit-form" method="post">
  <input type="text" name="username" pattern="[A-Za-z]{3,}" title="Only letters are allowed, minimum 3 characters" required>
  <input type="submit" value="Submit">
</form>

Minlength and maxlength attributes

The minlength and maxlength attributes specify the minimum and maximum number of characters allowed in an input field.

<form action="/submit-form" method="post">
  <input type="text" name="username" minlength="3" maxlength="15" required>
  <input type="submit" value="Submit">
</form>

Min and max attributes

The min and max attributes specify the minimum and maximum values allowed in an input field. They are commonly used with number and date input types.

<form action="/submit-form" method="post">
  <input type="number" name="age" min="18" max="100" required>
  <input type="submit" value="Submit">
</form>

Step attribute

The step attribute specifies the interval between legal numbers in an input field. It is commonly used with number and date input types.

<form action="/submit-form" method="post">
  <input type="number" name="quantity" min="1" max="10" step="1" required>
  <input type="submit" value="Submit">
</form>

Conclusion

HTML5 form validation attributes provide a powerful way to ensure that user input meets the required criteria before submission. By utilizing these attributes, developers can enhance the user experience and ensure data accuracy.

Comments