Contact form
Angular Bootstrap 5 Contact form component
A typical subscription form used when subscribing to a newsletter, asking a question in a FAQ section, or leaving a testimonial / review for a product.
To learn more read Docs.
Prerequisites
Before starting the project make sure to install the following utilities:
- Node LTS environment (12.x.x recommended)
- Express- setting the server
- Express-validator - for validating the form
- Nodemailer - for sending mails
- Multer - for handling multiparts request (reading FormData)
- Dotenv - for loading environment variables
- Cors - for enabling CORS (Cross-origin resource sharing)
Within this tutorial we are using the Material Design for Bootstrap library, you can download it for free from here. Without the library, the form will still work — however it may look and behave differently. It's recommended to use this library along with the tutorial.
Form HTML
First, create basic contact form which will be our base for validating and sending data.
Copy and paste the following HTML and JavaScript code into your file (e.g. index.html
):
Frontend validation
Our form now works fine. However currently if the user makes a mistake by clicking send without filling in the form first, this will result in sending an empty email. The other potential problem is that user might make a mistake in his email address so he would never get a response from us.
MDB Validation
MDBootstrap form components provide built-in validation which can be used to validate user data before sending email via PHP script. Read more about MDBootstrap form validation here.
In the example below all inputs were marked as required, and JavaScript code enabling custom MDB Form Validation was added.
Custom Validation
If you don't want to use MDB default validation and want to create your own functionality instead, you have to change the behavior of the form submission. So first change the existing code in our JavaScript.
Create NodeJS server file
Create a new file called server.js
inside your application's root directory.
If you haven't installed the express, nodemailer, body-parser and other necessary packages from the npm repository so far, do so immediately using the following command in your application terminal: