Forms and Input Validation


Concept Overview
In this topic of today, we will get to explore the following:
Understanding HTML Forms
JavaScript and Form Handling
Form Validation
Let’s get to it.
Understanding HTML Forms
HTML is the foundation of web development, acting as the backbone of every website you visit on the internet. Among its myriad features, HTML forms stand out as a crucial component for interactive and dynamic websites, enabling users to send data to web servers.
A form on a web page is a section that contain input elements where users can enter data, which can then be submitted to a server for processing. Think of a form as a digital equivalents of paper questionnaires.
Key uses of Forms
Use registration / Login.
Contact forms.
Search bars / sections.
Surveys.
Shopping Carts and checkouts.
A form begins and ends with the <form>
tag. All interactive fields (such as text fields, check-boxes, radio buttons, submit buttons, etc.) go inside this tag.
<form>
<!-- Your inputs go here -->
</form>
The <form>
has some other attributes such as:
action
: This is theURL
to send form data to.method
: Can either be “GET”(data in URL) or “POST”(data in body). read the article on HTTP methods to understand more about methods.target
: This is where to display the response (_self
,_blank
, etc).enctype
: This is the encoiding type (used with file uploads). example
<form action="https://example.com/register" method="POST" target="_blank">
Common form controls (inputs)
Text Input: Used for single line input.
<input type="text" name="firstname" placeholder="Enter your name" />
type=”text”
: This shows that it is a single line input.name=”firstname”
: Name of the input (used when submitting)placeholder
: Shown inside the box until user types something.Password Input: It obscures/hides the characters typed by the user.
<input type="password" name="password" />
Radio Buttons: Used when one has to pick one option out the many available options.
<label><input type="radio" name="gender" value="male" /> Male</label> <label><input type="radio" name="gender" value="female" /> Female</label>
Checkboxes: Unlike radio buttons, checkboxes allow multiple options to be selected.
<label><input type="checkbox" name="subscribe" value="yes" /> Subscribe to newsletter</label>
Dropdown(select): Drop downs provide a list of options where a user has to pick one option.
<select name="country"> <option value="kenya">Kenya</option> <option value="nigeria">Nigeria</option> </select>
Textarea (Multiline Input): These are used for longer text like comments and feedback.
<textarea name="message" rows="4" cols="30"></textarea>
Submit Button: It sends the form data to the server.
<input type="submit" value="Send" />
Reset Button: Used to clear form fields to their default values after a submission.
<input type="reset" value="Clear Form" />
Example of a complete form:
<form action="/register" method="POST">
<label>Name: <input type="text" name="name" required /></label><br>
<label>Email: <input type="email" name="email" required /></label><br>
<label>Gender:
<input type="radio" name="gender" value="male" /> Male
<input type="radio" name="gender" value="female" /> Female
</label><br>
<label>Country:
<select name="country">
<option value="kenya">Kenya</option>
<option value="uganda">Uganda</option>
</select>
</label><br>
<label>
<input type="checkbox" name="subscribe" value="yes" /> Subscribe
</label><br>
<input type="submit" value="Register" />
</form>
When the form is submitted, the browser sends the data as name=value
pairs and therefore the name attribute is critical. Without it, the input’s data won’t be sent.
POST /register HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=James&email=james@example.com&gender=male
JavaScript Form Handling
The <form>
elements has two important attributes: action
and method
.
The
action
attribute specifies a URL that will process the form submission. It can URL in the form of“/signup”
or“https://example.com/signup“
The
methods
attribute specifies the HTTP method to submit the form with. It can either beGET
orPOST
.
The JavaScript HTMLFormElement
used to represent the form has the following attributes.
action
: Which is the URL that processes the form data. It is the same to the action attribute of the<form>
element.method
: Is the HTTP method which is equivalent to themethod
attribute of the <form> element.submit()
: The method which submits the form.reset()
: The method which resets the form.
To reference the <form>
element, JavaScript uses the getElementById()
method of the DOM to select the form to submit. e.g.,
const form = document.getElementById('register');
When a form is submitted by clicking the submit button, the browser sends the form data to the server. If the submit button has focus and you press the Enter
key, the browser also submits the form data.
When you submit the form, the submit
event is fired before the request is sent to the server. This gives you a chance to validate the form data, and if the form data is invalid, you can stop submitting the form.
To add an even listener to the submit event, we use the addEventListener()
method of the form element as follows:
const form = document.getElementById('signup');
form.addEventListener('submit', (event) => {
// handle the form data
});
To prevent the form from being submitted, we call the event.preventDefault()
method of the form if data is invalid.
form.addEventListener('submit', (event) => {
// stop form submission
event.preventDefault();
});
To submit the form in JavaScript, we call the submit()
method of the form object. Remember that form.submit()
doesn’t fire the submit
event, and therefore, the form should always be validated before calling the method.
form.submit();
Form Validation
When you visit some of these common websites with registration or login forms, you may notice that they provide you with a feedback whenever you enter data in a format they don’t expect.
You may see things such as:
This field is required.
Please enter your phone number in format “xxx xxx xxx“
Please enter a valid email address. etc
This is what we refer to as form validation. When you enter data, the browser and web server will check if the data is in the correct format and within the constraints set by the application.
Validation done on the browser is called client-side validation while that done on the server is referred to as the server-side validation. If the information is correctly formatted, the application allows the data to be submitted to the server and it’s saved to the database. if the information is wrongly formatted, it gives user an error message explaining what needs to be corrected, and lets them try again.
The two main types of client side validation include:
HTML form validation where the HTML form attributes can define which form controls are required and which format the user entered data must be in to be valid.
JavaScript form validation where JavaScript is used to customize HTML form validation.
HTML form validation
HTML form validation has the form controls feature which is the ability to validate user data without depending on JavaScript. It is done using validation attributes such as:
required
: Specifies whether a form field needs to be filled in before the form is submitted.minlength
andmaxlegnth
: Specifies the minimum and maximum length of text data (string).min
,max
andstep
: specifies the minimum and maximum values of numerical input types, and the increment, or step for values starting from minimum.type
: Specifies whether the data needs to be a number, email address or some other type.pattern
: Specifies the regular expression that defines a pattern the entered data needs to follow.
JavaScript form validation
Let’s explore different ways of doing this:
Constraints validation API
The constraints validation API consists of methods and properties available on form element DOM interfaces such as HTMLButtonElement, HTMLFieldElement, HTMLInputElement, HTMLSelectElement, and HTMLTextAreaElement.For instance:
validationMessage
returns a localized message describing the validation constraints that the control doesn’t satisfyvalidity
returnsValidityState
object that contains several properties describing the validity state of the element.willValidate
returns true if the element will be validated when the form is submitted; false otherwise.
Implementing using customized error message
Customizing error messages is another common use of Constraints validation API. Here is a walk through.
We will use the HTML below:
<form>
<label for="mail">
I would like you to provide me with an email address:
</label>
<input type="email" id="mail" name="mail" />
<button>Submit</button>
</form>
And the JavaScript will be as follows:
const email = document.getElementById("mail");
email.addEventListener("input", (event) => {
if (email.validity.typeMismatch) {
email.setCustomValidity("I am expecting an email address!");
} else {
email.setCustomValidity("");
}
});
Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed.
Inside the contained code, we check whether the email input's validity.typeMismatch
property returns true
, meaning that the contained value doesn't match the pattern for a well-formed email address. If so, we call the setCustomValidity()
method with a custom message. This renders the input invalid, so that when you try to submit the form, submission fails and the custom error message is displayed.
Subscribe to my newsletter
Read articles from Lord Abiolla directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Lord Abiolla
Lord Abiolla
Passionate Software Developer with a strong enthusiasm for data, technology, and entrepreneurship to solve real-world problems. I enjoy building innovative digital solutions and currently exploring new advancements in data, and leveraging my skills to create impactful software solutions. Beyond coding, I have a keen interest in strategic thinking in business and meeting new people to exchange ideas and collaborate on exciting projects.