Javascript form validation
Instructions
In this course, we will see how to validate some of the most common inputs and return an error message
before sending data to the server. Here is a simple example of a form.
We won't discuss the HTML/CSS part, but if you are interested you can find the complete code here.
JS
let Name = document.querySelector("#Name"),
User_Name = document.querySelector("#User_Name"),
Password = document.querySelector("#Password"),
Confirm_Password = document.querySelector("#Confirm_Password"),
Birthdate = document.querySelector("#Birthdate"),
Email = document.querySelector("#Email"),
Phone_Number = document.querySelector("#Phone_Number"),
Submit_Btn = document.querySelector("#Submit_Btn"),
small = document.querySelector("small");
Explanation
- First, we have to fetch all the inputs that we want to check their inputs.
- We also have to fetch the button to change its default behavior.
- Finally, a small tag is added at the end (under the submit button) to show eventual errors.
- At first, this small tag is empty.
JS
Submit_Btn.addEventListener("click", (event) => {
event.preventDefault();
checkInputs();
});
Explanation
- Here, we are just registering an event on the submit button.
- It will first stop the default behavior on this button (using event.preventDefault();) which is sending data to the server.
- Then, it will call a function (using checkInputs();) that we implemented below to check all the input fields.
JS
function checkInputs() {
// get the values from the inputs
const NameValue = Name.value.trim();
const User_NameValue = User_Name.value.trim();
const PasswordValue = Password.value.trim();
const Confirm_PasswordValue = Confirm_Password.value.trim();
const BirthdateValue = Birthdate.value.trim();
const EmailValue = Email.value.trim();
const Phone_NumberValue = Phone_Number.value.trim();
.........
Explanation
- At the beginning of the checkInputs() function, we will retrieve the values inside the input fields.
- After that, we use the built-in trim() method to delete the blank space before and after the text.
- We declared these values as constants, so they won't be altered before checking them.
JS
if (NameValue === "") {
// show error
// add error class
setErrorFor(Name, "Name cannot be blank");
} else {
// add success class
setSuccessFor(Name);
}
Explanation
We will start by checking the Name input field. If it is empty, we will call a function (using
setErrorFor();)
to show an error message and add an error class to the input field. Otherwise, we will call another
function
(using setSuccessFor();) to add a success class to the input field.
- These functions are implemented below.
- They will add a class to the input field to change its color and show an error message.
- They will also change the small tag to show the error message.
JS
function setErrorFor(input, message) {
// add error message inside small
small.innerText += "\n" + message;
// add error class
input.className += " error";
}
function setSuccessFor(input) {
input.className += " success";
}
Explanation
Here is the implementation of the setErrorFor() and setSuccessFor() functions.
See the details in the code below.
- They will add a class to the input field to change its color and show an error message.
- They will also change the small tag to show the error message.
See the details in the code below.
JS
.error {
color: red;
background-color: rgb(255 0 0/ 0.1);
border: 1px solid red;
}
.success {
color: green;
background-color: rgb(0 255 0/ 0.1);
border: 1px solid green;
}
Explanation
Here the two classes that we will add to the input fields.
They will change the border color and the background color of the input field, as well as the text color.
They will change the border color and the background color of the input field, as well as the text color.
JS
if (EmailValue === "") {
setErrorFor(Email, "Email cannot be blank");
} else if (!isEmail(EmailValue)) {
setErrorFor(Email, "Email is not valid");
} else {
setSuccessFor(Email);
}
Explanation
In the case of the email and the phone number, we will use a regular expression to check if the
input is
valid.
These regular expressions are implemented with the isEmail() function and isPhone_Number() function.
These regular expressions are implemented with the isEmail() function and isPhone_Number() function.
- These functions will return true if the input is valid and false otherwise.
- They are implemented below.
The .test() method is a built-in method that will return true if the input matches the regular
expression and false otherwise.
Here, we are using regular expressions to check the email and the phone number.
The regular expression for the email is /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/ and for the phone number is /^([0]{1}[5-7]{1}[0-9]{8})$/.
In the case of the email, we are checking if it contains a-z, A-Z, 0-9, _, -, and . Then an @, then the same thing, then a dot and 2 to 5 characters.
The /^ and $/ are used to indicate the beginning and the end of the string.
The parantheses are used to group the characters.
The brackets are used to indicate a range of characters.
The + is used to indicate that the previous character can be repeated one or more times.
The {2,5} is used to indicate that the previous character can be repeated 2 to 5 times.
In the case of the phone number, we are checking if it starts with 05, 06, or 07 and has 8 digits after that.
Here, we are using regular expressions to check the email and the phone number.
The regular expression for the email is /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/ and for the phone number is /^([0]{1}[5-7]{1}[0-9]{8})$/.
In the case of the email, we are checking if it contains a-z, A-Z, 0-9, _, -, and . Then an @, then the same thing, then a dot and 2 to 5 characters.
The /^ and $/ are used to indicate the beginning and the end of the string.
The parantheses are used to group the characters.
The brackets are used to indicate a range of characters.
The + is used to indicate that the previous character can be repeated one or more times.
The {2,5} is used to indicate that the previous character can be repeated 2 to 5 times.
In the case of the phone number, we are checking if it starts with 05, 06, or 07 and has 8 digits after that.
JS
function isEmail(Email) {
return /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/.test( Email );
}
function isPhone_Number(Phone_Number) {
return /^([0]{1}[5-7]{1}[0-9]{8})$/.test(Phone_Number);
}
Explanation
These functions will return true if the input is valid and false otherwise.
They use regular expressions to check the input.
.test() is a built-in method that will return true if the input matches the regular expression and false otherwise.
They use regular expressions to check the input.
.test() is a built-in method that will return true if the input matches the regular expression and false otherwise.