Form Validation in HTML and JavaScript
Form validation is an essential part of web development. It ensures that the user inputs are correct and that they meet specified criteria before being processed. In this guide, we'll walk through the provided HTML and JavaScript code step-by-step to understand how form validation is implemented.
1. HTML Structure
In the HTML code, we create a simple registration form with three fields:
- Name: A text input for the user's name.
- ID: A text input for the user's ID.
- Number: A text input for the user's phone number.
Each input field has a corresponding <label> for accessibility and clarity. There’s also a submit button to send the form data.
2. CSS Styling
The CSS styles in the <style> section enhance the appearance of the form. The input fields have styles for:
- Width of 300px, padding, and margin for spacing.
- Border that changes color depending on whether the input is valid or invalid.
- A smooth transition effect when the border color changes.
The button has a hover effect which alters its background color when hovered over, improving the user experience.
3. JavaScript for Validation
The JavaScript code handles the form submission and validation:
- It first prevents the default action of the form submission using
event.preventDefault();. - It retrieves all input elements and the error display paragraph.
- It initializes a variable
isValidto keep track of the validation status.
4. Input Validation Logic
The validation process for each input is as follows:
- Name: Checks if the input is empty. If it is, it adds the
invalidclass and displays an error message. - ID: Similar to the name validation, it checks for emptiness.
- Number: Again, checks if the field is filled out.
If all fields are filled in, it adds the valid class to each input and displays an alert indicating successful submission.
5. Conclusion
This form validation technique is simple yet effective. It ensures that users provide essential information before the form can be submitted. As you gain more experience with JavaScript, you can explore more advanced validation techniques, such as checking formats or using regular expressions.
Happy coding!