Let’s create a contact form with validation in JavaScript.
To create a contact form with validation in JavaScript, you can follow these steps:
Create an HTML form with input fields for the user’s name, email, and message.
Add a
submit
button to the form.Add
id
attributes to the input fields and the submit button so that you can access them with JavaScript.A form element should have an
onsubmit
attribute that contains the name of the JavaScript validation function. This will cause the function to be called when the form is submitted.
The following is an example of how the code could look:
HTML:
Here is an example of how you can create an HTML contact form:
HTML
This will create a simple contact form with input fields for the user’s name, email, and message, and a submit button. The id
attributes are used to identify the elements in the JavaScript code and the onSubmit
the attribute is used to call the JavaScript validation function when the form is submitted.
You can customize the form to suit your specific needs by adding additional fields, changing the layout, etc.
CSS
Here is an example of how you can style the contact form using CSS:
Setting the width and margin of the form
Adding padding and a border to the form
Styling the labels and input fields
Adding a background color, font color, and padding to the submit button
You can customize these styles to suit your specific needs.
CSS
JavaScript
Create a JavaScript function that will be called on form submission. This function should validate the input fields and return
true
if the form is valid, orfalse
if the form is invalid.Use the
getElementById()
function to get the values of the input fields.Use
if
statements to check if the input fields are filled out correctly. For example, you can check if the name field is not empty and if the email field is a valid email address.If any of the input fields are invalid, display an error message.
Return
true
if all fields are valid, orfalse
if any of the fields are invalid.
An example of code would look like this:
JavaScript
This will prevent the form from being submitted if any of the validation checks fail. You can customize the validation checks to suit your specific needs.
Here is the complete JavaScript code for the contact form validation:
CodePen:
Additional Resources:
If you are looking for a simple contact form check this one:
For a more detailed validation form, check out this one:
Master JavaScript Form Validation by Building a Form from Scratch
Follow Ishrat Umar for more!