How to implement client-side form validation with JavaScript

0

JavaScript is one of the most popular and versatile programming languages ​​you can get started with today. It is rightly said that this programming language is the language of the web and that it is essential for adding interactivity to your websites.

The form element is one of the most used HTML elements on websites. These forms take user data and process it in the browser or server. However, it is important to validate these entries to resolve security issues and unwanted bugs.

Understanding DOM manipulation

Before proceeding with the implementation of client-side form validation with JavaScript, it is essential to understand the document object model, commonly known as “DOM”. The DOM is a standardized API that allows JavaScript to interact with the elements of an HTML web page.

Learn more: The Hidden Website Hero: Understanding the DOM

To add event listeners and retrieve user input, you will need to understand the basics of DOM manipulation. Here’s an example that shows how you can edit web page content using the DOM API and JavaScript:







Document





In the code above, the

the tag has an identifier of paragraph. When writing JavaScript code, you can access this element by calling the document.getElementById (‘paragraph’) method and manipulating its value.

Now that you’ve got the basics of DOM manipulation, let’s go ahead and implement form validation.

Form validation with JavaScript

There are different types of entries that you can take from a user. Text type, email type, password type, radio buttons, and checkboxes are some of the most common you may come across. Because of this vast majority of input types, you will need to use different logic to validate each one.

Before we get into validation, let’s take a moment to understand HTML forms and their importance. HTML forms are one of the primary ways of interacting with the website as they allow you to enter your data, apply changes, invoke pop-ups, submit information to a server, etc.

HTML The element is used to create these forms for users. Here’s how to validate the inputs of an HTML form:

1. Email validation

Whether you’re building an authentication system or just fetching user emails for your newsletter, it’s important to validate the email before you can store it in your database or process it. To check if an email meets all the requirements, you can use a regular expression.

HTML:

JavaScript:

const emailInput = document.getElementById('email');
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-][email protected][a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/;
if (!emailInput.value.match(emailRegex)) {
alert('Invalid email address.');
}

2. Password validation

Passwords are crucial data that requires a special type of validation to ensure its security. Consider a registration form that has two fields: the password and confirmation fields. To validate these input pairs, here are some things to consider:

  • Password must be more than 6 characters long.

  • The password value and the password confirmation field must be the same.

HTML:


JavaScript:

const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirm-password').value;
if (password.value !== confirmPassword.value) {
alert('Entered passwords do not match');
}
if (password.length < 6) {
alert('Password must be more than 6 characters long')
}

3. Radio input validation

HTML radio input is a special type of graphical control element that allows the user to choose a single option from a predefined set of mutually exclusive options. A common use case for such an entry would be gender selection. To validate such an entry, you will have to check if at least one of them is selected.

This can be achieved using logical operators such as AND (&&) and not (!) operator in this way:

HTML:






JavaScript:

const genders = document.getElementsByName("gender");
const validForm = false;
let i = 0;
while (!validForm && i < radios.length) {
if (radios[i].checked) validForm = true;
i++;
}
if (!validForm) alert("Must check some option!");

4. Select Entry validation

The The HTML element is used to create a drop-down list. The tags inside the item define the options available in the drop-down list. Each of these tags have a value attribute associated with them.

For the default or initial option, you can set its value to an empty string so that it is considered an invalid option. For all other options, set an appropriate value attribute. Here is an example of how you can validate a input element:

HTML:

JavaScript:

const title = document.getElementById('title');
if (title.value = "") {
alert('Please select a title');
}

5. Validation of the check boxes

Checkbox type input items are displayed by default as boxes that are checked or checked when enabled. A checkbox allows you to select unique values ​​to submit in a form. Checkboxes are a common choice for the “accept terms and conditions” entry.

To find out whether a box is checked or not, you can access the checked attribute on the entry of the checkbox. Here is an example :

HTML:


JavaScript:

const terms = document.getElementById('terms');
if (!terms.checked) {
alert('Please agree to the terms and conditions to proceed further.');
}

Prevention is better than cure

It is always recommended that you validate any input you receive from a visitor to provide a safe and secure experience. Hackers always attempt to enter malicious data into input fields to perform cross-site scripting attacks and SQL injections.

Now that you understand how to validate your HTML inputs, why not give it a try by creating a form and implementing the strategies you saw above?


An application form
How to create a form in HTML

Allow your users to enter data on your websites with HTML forms.

Read more


About the Author


Source link

Leave A Reply

Your email address will not be published.