Multiple Form Validation in JS using Class - javascript

I want to validate 2 html forms - First form is on the FAQ page and the second form is on the contact us page. Both forms have name and phone as common input fields so I want to validate both form conveniently in JS by using Class.
My JS code is as follows for validating Name and Phone input field for FAQ form.
class FormValidate {
constructor(nameField, phoneField, emailField, form) {
this.nameField = nameField; // name input field
this.phoneField = phoneField; // phone input field
this.emailField = emailField; // email input field
this.form = form;
}
// method for validation of name input
validateName(nameField) {
const regName = new RegExp("^[a-zA-Z\\s]*$");
let isNameValid = false;
let name_z = nameField.value.trim(); // input value of Name input field
let isNameHasValidLength = name_z.length < 3 || name_z.length > 20 ? false : true;
// Name input field is not empty and contain proper data -> Not Empty && value must be between 3 to 20 characters && follow reg expression for validation
if( !(name_z === '') && isNameHasValidLength && (regName.test(name_Z)) ){
isNameValid = true;
}
return isNameValid;
}
validatePhone(phoneField) {
let isPhoneValid = false;
let phone_z = phoneField.value.trim(); // input value of Phone input field
let isPhoneHasValidLength = phone_z.length < 10 || phone_z.length > 13 ? false : true; // making sure that phone number is between 10 to 13 digits -> +91 and rest 10 digits
const regPhone = new RegExp("^([0|+[0-9]{1,5})?([7-9][0-9]{9})$");
// Validating Phone Number -> Not Empty && Must have 10 to 13 digits only && follow reg expression for validation
if( !(phone_z === '') && isPhoneHasValidLength && regPhone.test(phone)) {
isPhoneValid = true;
}
return isPhoneValid;
}
}
let faqForm = new FormValidate(document.querySelector('#name'), document.querySelector('#phone'), null, document.querySelector('#faq-form'));
faqForm.form.addEventListener('submit', function(e) {
let nameOkay;
let phoneOkay;
let submitOkay;
nameOkay = faqForm.validateName(faqForm.nameField);
phoneOkay = faqForm.validatePhone(faqForm.phoneField);
submitOkay = nameOkay && phoneOkay;
// Prevent form submission if form input is not okay
if (!submitOkay) {
e.preventDefault();
}
});
HTML form code -
<form id="faq-form" action="mail-faq.php" method="POST">
<div class="faq-form-group"> <span class="faq-form-span-text">Name</span>
<input type="text" placeholder="i.e, John Smith" name="name" id="name" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Phone</span>
<input type="text" placeholder="+91 123456789" name="phone" id="phone" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Message</span>
<textarea placeholder="Your question" name="message" id="message" autocomplete="off" required></textarea>
</div>
<div class="faq-form-group">
<button class="faq-form-submit-btn" id="submit" type="submit" name="submit">Submit </button>
</div>
</form>
The problem is that nameField.value.trim(); and phoneField.value.trim(); statements are returning value - "" Which makes the validation false.
How can I fix this problem?

When you correct the typo here in (regName.test(name_Z)) (lowercase z) then the trimed vars are as expected (not "")...

Related

How to perform string methods on function parameter in javascript

I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}

Post a form after javascript check

I would like to send a form after javascript validation in validateLengths() function.
If I fill a form action the form is send anyway if I don't specify javascript:void(0)
Here is my code so far...
Currently I'm just able to alert "submit form".
Sorry, I'm a noob in javascript.
Thank you for any related information.
Have a nice day.
Nicolas.
function validateLengths() {
let fnameCap = document.getElementById("firstName").value;
let lnameCap = document.getElementById("lastName").value;
if (fnameCap.length < 4 ) {
alert("First name must be atleast 4 characters. ");
return false;
}
if (lnameCap.length < 6) {
alert("Last name must be atleast 6 characters. ");
return false;
}
if(fnameCap.length >= 4 && lnameCap.length >= 6){
alert ("submit form"); // don't know how to send form here
}
}
function capitalize(){
let first = document.getElementById("firstName");
let last = document.getElementById("lastName");
let fcapitalized = first.value.toUpperCase();
let lcapitalized = last.value.toUpperCase();
first.value = (fcapitalized);
last.value = (lcapitalized);
validateLengths();
}
<form action="javascript:void(0)" id="theForm" title="form1">
<input name="firstName" type="text" id="firstName" value="At least 4 chars">
<br>
<input name="lastName" type="text" id="lastName" value="At least 6 chars">
<br>
<input type="submit" name="submit" id="submit" value="Submit" onClick="javascript:capitalize()">
</form>

How can this Javascript code handle the if/else statements better, or possibly use switches?

First off, if this is against the rules, or frowned upon I'm very sorry and feel free to downvote/close. I'm desperately stuck.
I'm having trouble with an HTML page I wrote which is supposed to consist of inputs with certain requirements, adding div's to display error messages , and automatically update those error messages onblur. The assignment was made to test our javascript skills, and thus must be completely validated through javascript.
Here are a few of the guidelines...
validating the form for four separate things:
presence of required fields
equality of password fields
conformance to a password policy (one uppercase, one number, length > 7)
validity of the email address
When any one of these are violated, I should deactivate the form’s submit button so that it is not clickable and add a child "div" to the error-display containing an error message describing the situation.
The code seems correct to me, and works spontaneously, but i believe since javascript is looked at one line at a time it isn't displaying error messages correctly or even getting to certain parts of my code at all.
Here is my large chunk of javascript code, I am mainly looking for a way to break out of these if/else blocks that my code seems stuck in:
function formValidation() {
var form = document.getElementById('project-form');
var username = document.getElementById('username');
var name = document.getElementById('name');
var phone = document.getElementById('phone-number');
var email = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirmation = document.getElementById('password-confirmation');
var submit = document.getElementById('submit-btn');
var errorDisplay = document.getElementById('error-display');
var missingFieldBoolean = false;
var passwordMismatchBoolean = false;
var isUpper = false;
var isNumber = false;
var passwordLength = false;
var validEmail = false;
var createDiv = document.createElement("DIV");
var passwordConstraint, passwordConstraintError;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
//Checks all fields for empty values and updates error div
if (username.value.length == 0 || name.value.length == 0 || email.value.length == 0 || password.value.length == 0 || passwordConfirmation.value.length == 0) {
missingField = errorDisplay.appendChild(createDiv);
missingField.setAttribute("id", "required-field-error");
missingFieldError = document.getElementById('required-field-error');
missingFieldError.innerHTML = "Missing Fields: ";
if (username.value.length == 0) {
missingFieldError.innerHTML += "Username - ";
}
if (name.value.length == 0) {
missingFieldError.innerHTML += "Full Name - ";
}
if (email.value.length == 0) {
missingFieldError.innerHTML += "Email - ";
}
if (password.value.length == 0) {
missingFieldError.innerHTML += "Password - ";
}
if (passwordConfirmation.value.length == 0) {
missingFieldError.innerHTML += "Password Confirmation - ";
}
} else {
errorDisplay.removeChild(missingFieldError);
missingFieldBoolean = true;
}
//Checks password vs password confirmation to see if they match, else updates error div
if (password.value != passwordConfirmation.value) {
passwordMismatch = errorDisplay.appendChild(createDiv);
passwordMismatch.setAttribute("id", "password-mismatch-error");
passwordMismatchError = document.getElementById('password-mismatch-error');
passwordMismatchError.innerHTML = "The Password and Password Confirmation do not match. Please re-enter.";
} else {
errorDisplay.removeChild(passwordMismatchError);
passwordMismatchBoolean = true;
}
//for loop to iterate through password to check for required characters, else updates error div
for (var index = 0; index < password.value.length; index++) {
if (password.value.charAt(index) == password.value.charAt(index).toUpperCase) {
isUpper = true;
}
if ("0123456789".indexOf(password.value.charAt(index)) > -1) {
isNumber = true;
}
if (password.value.length > 7) {
passwordLength = true;
} else {
passwordConstraint = errorDisplay.appendChild(createDiv);
passwordConstraint.setAttribute("id", "password-constraint-error");
passwordConstraintError = document.getElementById('password-constraint-error');
passwordConstraintError.innerHTML = "The Password must be 8 characters long, with one uppercase letter and one number. ";
}
}
//checks if password constraints are met and removes div if true
if (isUpper && isNumber && passwordLength) {
errorDisplay.removeChild(passwordConstraintError);
}
//checks email, if invalid it adds error div, else it removes the div ***NOT WORKING***
if (!(mailformat.test(email.value))) {
invalidEmail = errorDisplay.appendChild(createDiv);
invalidEmail.setAttribute("id", "invalid-email-error");
invalidEmailError = document.getElementById('invalid-email-error');
invalidEmailError.innerHTML = "Please enter a valid email address.";
} else {
errorDisplay.removeChild(invalidEmailError);
validEmail = true;
}
//if all requirements are met and true, submit button becomes enabled ***NOT WORKING***
if (isUpper && isNumber && passwordLength && missingFieldBoolean && passwordMismatchBoolean && validEmail) {
submit.disabled = false;
}
}
<div id="error-display"></div>
<br>
<form id="project-form" action="/submit.php" method="get" onclick="formValidation()">
<label>Username:</label>
<input id="username" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Full Name:</label>
<input id="name" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Phone Number:</label>
<input id="phone-number" type="tel">
<br>
<label>Email:</label>
<input id="email" type="email" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Password:</label>
<input id="password" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<label>Confirm Password:</label>
<input id="password-confirmation" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<br>
<input id="submit-btn" type="submit" value="Submit" disabled>
</form>
Thanks a lot in advance, and again sorry if i'm breaking the rules.
I would put all the inputs into an object instead, that way you could automatically iterate over the object.
const fieldValues = [
'username',
'name',
'phone-number',
'email',
'password',
'password-confirmation',
]
.reduce((fieldsSoFar, fieldName) => {
fieldsSoFar[fieldName] = document.getElementById(fieldName).value;
return fieldsSoFar;
}, {});
const missingFieldsStr =
Object.entries(fieldValues)
.filter(([, fieldValue]) => fieldValue.length === 0)
.map(([fieldName]) => {
const words = fieldName.split(' ');
const upperWords = words.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
return upperWords;
})
.join(', ');
if (missingFieldsStr) {
// display it
}
// skipping some lines...
const hasUpper = /[A-Z]/.test(fieldValues.password);
const hasNumber = /[0-9]/.test(fieldValues.password);
And so on.
Don't implicitly create global variables - strongly consider using a linter.
Only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.

NIC and username validation field

I have two fields, the NIC and the username. Their validation are
NIC check for numbers or characters
username field must contain more than 8 characters including the date
of birth from the NIC.
So far I tried this for my NIC.
function validateNIC()
{
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
message1.innerHTML="Length must be 14 characters";
} else{
message1.innerHTML="Length is good";
}
}
<div class="form-group">
<label for="username"><span class="req">* </span> NIC NUMBER:</label>
<input class="form-control" type="text" name="NIC" id = "NIC" required onkeyup = "validateNIC();" maxlength=14 />
<span id="message1"></span>
</div>
And for my username I tried this.
function Validate(txt) {
txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
}
<div class="form-group">
<label for="username"><span class="req">* </span> User name:</label>
<input class="form-control" type="text" name="username" id="txt" onkeyup="Validate(this)" maxlength=14 required />
<div id="errLast"></div>
</div>
My validation for the NIC is not quite working.It keeps showing
"Length must be 14 characters" even if the length is good.
And for the username part, can anyone tell me how to do it ? Is
there an array I must do or something ? An example of the NIC is
T2108974302906 where 210897 is the DOB.
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
Here NIC refers to the DOM element, not the value of that input element.
You want to use nic.value.length.
As for the username, your RegEx looks strange [^a-zA-Z-'\n\r.]. This set matches characters that are not in the set. Why did you put \n and \r?
Anyway, if you are using a <form> element to submit these field, I suggest you use pattern attribute. You can test yoru patterns on http://regex101.com/
To extract the DOB:
<input pattern="^T[0-3]\d[0-1]\d{10}$">
validateNIC() {
var nic = document.getElementById('NIC');
var isValid = /^T[0-3]\d[0-1]\d{10}$/.test(nic.value);
var dob = nic.value.substring(1, 7);
}
var nic = document.getElementById('NIC');
This statements gets the input element - not its value. You need to get its value as such:
var nic = document.getElementById('NIC').value;
Then, you can compare the length to 14. I would also suggest using !== instead of !=.
Username validation - why are you replacing the value if you're trying to validate? And why is your max value 14 and not 8?

Individual error messages for empty form fields using JavaScript

I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.
My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.
My HTML:
<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
And my JavaScript:
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else {return true;}
}
</script>
Thanks for your help.
Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.
To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.
I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.
Live Demo:
document.getElementById("english_registration_form").onsubmit = function () {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
var submit = true;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
submit = false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
submit = false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
submit = false;
}
return submit;
}
function removeWarning() {
document.getElementById(this.id + "_error").innerHTML = "";
}
document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
JSFiddle Version: https://jsfiddle.net/xga2shec/
First of all, we change your function validateForm so it can handle multiple validations.
Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.
And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.
Take a look at the code commented, and see the working version in action!
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
you have to use style.display="none" to hide error
and style.display="block" to show error
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (x != null || x != "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="none";
return false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="block";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (y != null || y != "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="none";
return false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="block";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else if (z != null || z != "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="none";
return false;
}
else {return true;}
}
</script>
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>

Categories

Resources