Building an Input Form Function based Form Validation with Regular Expressions (Regex)
how to create a functional input form with regex validation using HTML, CSS, and JavaScript
- HTML File (index.html):
This is the structure of your web page. It contains the form elements and provides the basic layout for your input form. Here's how it's organized:
- The <head> section includes necessary meta tags, title, external CSS and JavaScript files, and fonts for styling.
- The <body> section is divided into a <div> with a class of container. This is where your form resides.
Inside the <div class="container">, you've structured your form as follows:
- You have a <form> element that encloses your form content.
- You've included a heading, labels, input fields, and radio buttons to collect user information.
- You've added the necessary attributes like id, placeholder, and name to your input fields for identification and functionality.
- You've also included a script that enables the preview of uploaded images.
CSS File (style.css):
This file provides the styling and visual appearance for your input form. It uses various classes to target and style specific elements within your HTML. Let's break down some of the key parts:
- You set global styles using * to reset margins and paddings and ensure box-sizing consistency.
- The .container class styles your form container, including background color, border-radius, and positioning.
- Different elements such as headings, labels, and inputs are styled for fonts, colors, and spacing.
- You've created specific styles for radio buttons, file uploads, and phone number input fields.
- Classes like .success and .error handle the appearance of success and error states for inputs.
- Media queries adjust styles for different screen widths, ensuring a responsive design.
JavaScript File (app.js):
Your JavaScript file adds functionality to your form, including form validation and handling of user interactions:
- You've declared variables to store references to form elements using document.getElementById and document.getElementsByClassName.
- You've defined functions to handle success messages, error messages, and form submission.
- The setData function displays a success message when the form is submitted successfully.
- The setSuccess function checks if all input fields are in a success state before displaying the success message.
- The validation function checks user inputs against predefined rules, showing error or success states as appropriate.
- Regular expressions (isEmail, regex, cnicRegex) are used to validate email, phone numbers, and CNIC numbers.
- Event listeners are set up to trigger validation on form submission and phone number input.
- The previewImage function previews uploaded images and displays their sizes.