Page 154 - CITS - Computer Software Application -TT
P. 154
COMPUTER SOFTWARE APPLICATION - CITS
function showSuccess(input) {
return showMessage(input, “”, true);
}Code language: JavaScript (javascript)
The hasValue() function
The hasValue() function checks if an input element has a value or not and shows an error message using the
showError() or showSuccess() function accordingly:
function hasValue(input, message) {
if (input.value.trim() === “”) {
return showError(input, message);
}
return showSuccess(input);
}Code language: JavaScript (javascript)
The validateEmail() function
The validateEmail() function validates if an email field contains a valid email address:
function validateEmail(input, requiredMsg, invalidMsg) {
// check if the value is not empty
if (!hasValue(input, requiredMsg)) {
return false;
}
// validate email format
const emailRegex =
/^(([^<>()\[\]\\.,;:\s@”]+(\.[^<>()\[\]\\.,;:\s@”]+)*)|(“.+”))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]
{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const email = input.value.trim();
if (!emailRegex.test(email)) {
return showError(input, invalidMsg);
}
return true;
}Code language: PHP (php)
The validateEmail() function calls the hasValue() function to check if the field value is empty. If the input field is
empty, it shows the requiredMsg.
To validate the email, it uses a regular expression. If the email is invalid, the validateEmail() function shows the
invalidMsg.
The submit event handler
First, select the signup form by its id using the querySelector() method:
const form = document.querySelector(“#signup”);Code language: JavaScript (javascript)
Second, define some constants to store the error messages:
const NAME_REQUIRED = “Please enter your name”;
const EMAIL_REQUIRED = “Please enter your email”;
const EMAIL_INVALID = “Please enter a correct email address format”;Code language: JavaScript (javascript)
Third, add the submit event listener of the signup form using the addEventListener() method:
141
CITS : IT&ITES - Computer Software Application - Lesson 37 - 46