@MahmoodHashem
Posted
Hello there
Congratulations on successfully finishing the challenge!
Your project is absolutely amazing.
Here are a few suggestions that can further enhance your project:
HTML comes with a built-in form validation API that is widely supported by modern browsers. This API allows you to perform client-side form validation without the need to write complex regular expressions. Instead, you can leverage the HTML's built-in validation attributes and properties to handle form validation.
The key steps to implement form validation using the HTML validation API and JavaScript are as follows:
Add Validation Attributes to the Form and Input Fields :
- Add the
noValidate
attribute to the<form>
element to disable the browser's default form validation behavior. - Add the
required
attribute to the input fields that should be mandatory. - Specify the appropriate
type
attribute for the input fields (e.g.,type="email"
for email fields) to enable built-in validation for the specific input type.
<form action="" noValidate>
<input
type="email"
required
id="email"
placeholder="[email protected]"
/>
</form>
Handle Form Submission with JavaScript :
- Add an event listener to the
submit
event of the form. - Inside the event listener, call the
preventDefault()
method to prevent the default form submission behavior. - Check the validity of the form fields using the
validity
property, which provides various sub-properties likevalueMissing
andtypeMismatch
. - Based on the validity state, you can display appropriate error messages or perform other actions.
const form = document.querySelector('form');
const email = document.getElementById('email');form.addEventListener('submit', (e) => {
e.preventDefault(); if (email.validity.valueMissing) {
// Display "Please fill out this field" error
} else if (email.validity.typeMismatch) {
// Display "Please enter a valid email address" error
} else {
// Form is valid, proceed with submission
}
});
Hope you found that helpful
Keep up the hard work