I have a form with five inputs with with two text fields one password field one email field and the other is a submit button and i want the form not to submit when the the fields are empty and also display first name cannot be empty, last name cannot be empty,email cannot be empty and password cannot be empty under each corresponding fields and also check if the email is in a right format .
I tried the code below expecting to display the messages in the p elements when the field is empty but instead the browser refreshes the page with displaying the message in the p elements
fname = document.querySelector("#first-name");
lname = document.querySelector('#last-name');
email = document.querySelector('#email');
password = document.querySelector("#password");
function formValidator() {
if (fname.value = '') {
document.getElementById('first-p').innerHTML = "First name cannot be empty"
};
if (lname.value = '') {
document.getElementById('last-p').innerHTML = 'Last name cannot be empty'
};
if (email.value = '') {
document.querySelector('#email-p').innerHTML = 'Email cannot be empty'
};
if (password.value = '') {
document.querySelector('#password-p').innerHTML = 'Password cannot be empty'
}
}
<form action="">
<label for="first-name">First name:</label>
<input type="text" id="first-name">
<p id="first-p"></p>
<br>
<label for="last-name">Last name:</label>
<input type="text" id="last-name">
<p id="last-p"></p>
<br>
<label for="Email">Email:</label>
<input type="email" name="" id="email">
<p id="email-p"></p>
<br>
<label for="password">Password:</label>
<input type="password" name="" id="password">
<p id="password-p"></p>
<br>
<input type="submit" value="Submit" onsubmit="formValidator()">
</form>
4
Answers
correct code is given below
A form by default on a submit refreshes the page
To prevent this, use
event.preventDefault()
All you have to do is to add
required
attribute to your inputs. no need to js.for example:
required
uses browsers default validation, which varies by the inputstype
Hope I helped.
First thing: As @mplungjan mentioned, you should be using the required attribute in the input fields.
Second: Sometimes we do things in our own way. So below is something you might try. I hope it will help.
You can try below:
I hope it will help. Thank you.