Bytes

Form Submission and Validation in HTML

Last Updated: 22nd June, 2023

Form Submission

When a user submits a form on a web page, the browser sends the data entered into the form to the web server for processing. The way the browser sends this data to the server is determined by the HTTP method used in the form's submission.

The two most common HTTP methods used for form submission are GET and POST.

GET is the default method for form submission. When a form is submitted using GET, the form data is appended to the URL as query parameters, and the browser sends a request to the server with this URL. GET requests are typically used for requesting resources from the server and are cached by the browser.

POST, on the other hand, sends the form data in the request body, and the data is not visible in the URL. POST requests are typically used for submitting data to the server, such as when creating a new record in a database. Unlike GET requests, POST requests are not cached by the browser and can also include file uploads.

In addition to GET and POST, there are other HTTP methods that can be used for form submission, such as PUT, DELETE, PATCH, and OPTIONS, depending on the functionality of the web application. However, these methods are less commonly used for form submission and are typically used for more specialized operations, such as updating or deleting data on the server.

Form Validation in HTML5

Form validation in HTML is the process of verifying that the data entered by a user in an HTML form is accurate, complete, and meets certain requirements before submitting it to a server for further processing. The validation is done to ensure that the data is in the correct format and meets the required standards before it is submitted.

HTML form validation can be done using various techniques such as client-side validation, server-side validation, and database validation. Client-side validation is done using JavaScript or HTML5 and can be done without submitting the form to the server. Server-side validation is done on the server after the form has been submitted, and database validation is done by checking the data against a database to ensure it meets the required standards.

By validating forms in HTML, you can help to ensure that the data submitted is accurate and complete, reducing errors and making it easier to process the data on the server. HTML5 provides a range of attributes and APIs that enable web developers to validate forms easily.

Here, we will look some important Client-side Validation with HTML5:

Required Fields

One of the most basic form validation techniques is to ensure that all required fields are filled out by the user. Required fields are those fields that must be filled out for the form to be submitted successfully. In HTML, you can use the "required" attribute to specify that a field is required. This attribute is available for input types such as text, email, number, and checkbox.

Example:

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

Minimum and Maximum Length

Another form validation technique is to set minimum and maximum length for input fields. This technique is useful when you need to ensure that users enter a certain amount of information. In HTML, you can use the "minlength" and "maxlength" attributes to set the minimum and maximum length of an input field.

Example:

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

Numeric Inputs

When you want the user to input numeric values, it is important to ensure that they only enter numbers. HTML provides the "type" attribute, which allows you to specify that an input field is for numeric input. You can also set minimum and maximum values for the input field.

<input type="number" name="age" min="18" max="100" required>Example:

Email Validation

Email validation is crucial when you want users to input their email addresses. Email validation ensures that the user enters a valid email address format. In HTML, you can use the "type" attribute to specify that an input field is for email input.

Example:

<input type="email" name="email">

Using Regular Expressions

Regular expressions are a powerful tool for validating complex input formats, such as phone numbers, postal codes, or credit card numbers. Regular expressions are patterns that match specific strings of text. You can use regular expressions in HTML5 pattern attribute to define the input format. Here are some examples:

  • Phone number pattern: The following regular expression matches a valid US phone number format:
<input type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
  • Postal code pattern: The following regular expression matches a valid US postal code format:
<input type="text" name="zipcode" pattern="[0-9]{5}" required>
  • Credit card pattern: The following regular expression matches a valid Visa credit card format:
<input type="text" name="creditcard" pattern="4[0-9]{12}(?:[0-9]{3})?" required>

Using the Constraint Validation API

The Constraint Validation API is a built-in JavaScript API that provides a more flexible and powerful way of validating forms on the client-side. It works by checking the validity of input elements against a set of constraints that you define. This approach is much more customizable and allows for more complex validation rules than the basic form validation techniques discussed earlier.

To use the Constraint Validation API, you need to access the validity property of the input element in JavaScript. The validity property contains a set of properties that describe the validity of the element. For example, you can use the following code to check if an input element is valid:

const input = document.getElementById('my-input');
if (input.validity.valid) {
  // input is valid
} else {
  // input is invalid
}

In addition to the validity property, the Constraint Validation API also provides a set of methods that you can use to trigger validation manually. For example, you can use the checkValidity() method to check if an input element is valid, or the reportValidity() method to show an error message if the input is invalid.

One of the most powerful features of the Constraint Validation API is the ability to define custom validation rules using the setCustomValidity() method. This method allows you to set a custom error message for an input element based on your own validation logic. For example, you can use the following code to set a custom error message for a password input that requires at least one uppercase letter:

const passwordInput = document.getElementById('password');
passwordInput.addEventListener('input', () => {
  const password = passwordInput.value;
  if (!password.match(/[A-Z]/)) {
    passwordInput.setCustomValidity('Password must contain at least one uppercase letter');
  } else {
    passwordInput.setCustomValidity('');
  }
});

This code adds an event listener to the password input that checks if the password contains at least one uppercase letter. If it doesn't, it sets a custom error message using the setCustomValidity() method. If the password is valid, it clears the error message by setting an empty string as the value of setCustomValidity().

Conclusion

Validating forms is an important part of creating a good user experience on the web. There are many different techniques and tools you can use to validate forms, depending on your needs and preferences. Basic form validation techniques like required fields, minimum and maximum length, numeric inputs, and email validation are simple and easy to implement, but they have limitations in terms of customization and complexity.

HTML5 provides some new input types that can help with basic form validation, and regular expressions can be used to validate more complex input patterns. The Constraint Validation API is a more powerful and flexible way of validating forms on the client-side, allowing you to define custom validation rules and error messages based on your own validation logic. By using a combination of these techniques, you can create forms that are both user-friendly and secure.

Module 5: Tables and Forms in HTML5Form Submission and Validation in HTML

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter