PDF

Understanding Basic Form Validation

In this tutorial, we will learn how to create a simple form with basic validation using HTML and JavaScript. This is especially useful for ensuring that users provide the required information before submitting a form.

Step 1: Setting Up the HTML Form

We start with a basic HTML structure that consists of a form with three input fields: Name, ID, and Number. Below is the structure:

<form id="simpleForm" class="register-form">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
</form>

This form structure allows users to enter their details.

Step 2: Adding CSS for Styling

We can improve the appearance of our form by styling it with CSS:

.register-form input {
    width: 300px;
    padding: 10px;
    margin: 5px 0;
    border: 2px solid #ccc;
    border-radius: 5px;
    outline: none;
}
.register-form input.valid {
    border-color: green;
}
.register-form input.invalid {
    border-color: red;
}

Here, we define styles for valid and invalid inputs. Valid inputs will have a green border, and invalid ones will have a red border.

Step 3: Implementing JavaScript Validation Logic

We need to add JavaScript to validate the form when the user submits it. We will check if each input field is filled out correctly. Here’s how we do it:

document.getElementById('simpleForm').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevents form from submitting immediately
    ... // Validation logic goes here
});

The validation logic checks whether the input fields are empty and updates their classes accordingly:

if (name.value.trim() === '') {
    name.classList.add('invalid');
} else {
    name.classList.add('valid');
}

This checks each input and adds the appropriate classes based on whether they contain values.

Step 4: Displaying Errors and Successful Submission

If any fields are invalid, we display an error message, and if all fields are valid, we can show a success message:

if (isValid) {
    alert('Form submitted successfully!');
}

All these elements combined help create a responsive and user-friendly form!

Conclusion

Now you have a simple form that validates user input before submission. This basic understanding of form validation will allow you to enhance your web applications and ensure data integrity. Keep practicing and expanding your skill set!


Ask a followup question

Loading...