JavaScript form validation second if statement not working - javascript

I'm starting simple JavaScript form validation. I write two statement, first if statement working well but second one is not. But this two if statement separately working. I don't understand what I'm wrong. Here is the HTML code:
<form id="loginForm" name="loginForm" method="post" action="my-profile.html">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="eMail" placeholder="abcde00#example.com" class="form-control" required="required" />
<span class="erRor" id="error1">Please input valid email address</span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="Password" name="password" id="pasSword" class="form-control" required="required" />
<span class="erRor" id="error2">Invalid email and password</span>
<span class="erRor" id="error3">This field should not be empty</span>
</div>
<div class="form-group">
<button type="submit" onclick="return validate();">Login</button>
</div>
</form>
JavaScript code here:
function validate(){
/* email validation */
var changeColor = document.getElementById("eMail");
var error1 = document.getElementById("error1");
var email1 = document.loginForm.email;
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
if(!re.test(email1.value)){
changeColor.style.border = "2px solid red";
error1.style.display = "block";
return false;
}
/* empty fild check for password field */
var pas = document.getElementById("pasSword");
var error3 = document.getElementById("error3");
var password = document.loginForm.password;
if(password.value === ""){
pas.style.border = "2px solid red";
error3.style.display = "block";
return false;
}
}
Please help me out of this.
Note: I want to learn "AS YOU TYPE JavaScript for validation". I haven't find any proper tutorial or desiccation.

You are using return false, hence second validation is not working.
Try this:
var valid = true;
if(conditoin_one){
valid = false;
// update error element
}
if(conditoin_two){
valid = false;
// update error element
}
return valid;

Related

preventDefault() cause problem on validating the form

the code below was written to validate simple html form with JavaScript and preventDefault() method means that if the required fields are empty then stop form submission and display error or otherwise submit the form if the required fields are not empty.
The problem comes when I click the submit button the form isn't working.
Can anyone please help me to solve the problem?
let form = document.getElementById("signUp");
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
function validateForm() {
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
e.preventDefault();
validateForm();
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
With e.preventDefault() you say that the form should not be submitted.
So you only want to call if in case the validation returns false.
Besides that, your uname and uemail is set before the form is submitted. So it won't contain the state of the input fields at the time the form is submitted. You have to move them into your validateForm function.
let form = document.getElementById("signUp");
function validateForm() {
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
if (!validateForm()) {
e.preventDefault();
}
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
And uname == " " does not test if the name is empty. It tests if it consists of one character that is a space. The same is for uemail == " ". You probably looking for uname.trim() == ""
As you need to verify the data on the server anyways. And in some way need to display an error if the validation fails on the server side.
It is often sufficient to rely on the HTML solutions to verify the form data (if the browser support is decent enough even if it is not complete).
Something like this:
.error {
display: none;
}
input:not(:placeholder-shown):invalid +.error {
display: block;
}
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName" placeholder="Name" pattern="^(?!^ +$)([\w -&]+)$" required>
<div class="error">Name must not be empty</div>
<br> Email: <input type="email" name="email" id="userEmail" placeholder="Email" required>
<div class="error">Email must be valid</div>
<button type="submit">sign up</button>
</form>
const form = document.getElementById("signUp");
form.addEventListener("submit", (e) => {
e.preventDefault();
if(validate()) {
form.submit()
}
});
const validate = () => {
const name = document.querySelector("#userName");
const email = document.querySelector("#email");
let hasError = false;
if(!(name.value && name.value.length > 4)) {
const nameErr = document.querySelector("#user-name-error");
nameErr.textContent = "Name is required";
hasError = true;
}
if(!(name.value && name.value.length > 0)) {
const emailErr = document.querySelector("#user-email-error");
emailErr.textContent = "Email is required";
hasError = true;
}
return !hasError;
};
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" />
<p id="user-name-error" style="color: red;"></p>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" />
<p id="user-email-error" style="color: red;"></p>
</div>
<button type="submit">sign up</button>
</form>
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" required minlength="4"/>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" required pattern="[^#]*#[^.]*\..*"/>
</div>
<button type="submit">sign up</button>
</form>
This is an example using only html, it is only for your use case of course if you want to add more complexe validation use javascript

My signup button disappears while filling out my password on a form

This is a two-part question.
Part 1. The passConfirm function that I currently have is there to make sure that the password and confirming password values match. Right now, when I type in my password the button disappears. The purpose of this function is to display a message while the user is creating a password and confirming it, that the password does or does not match. Does anyone know why that is happening based on the code I have?
Part 2. Is there a way to refactor my passConfirm function? I tried doing it by adding it to the validateForm function (Please see commented code for my example). It wasn't working tho.
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
event.preventDefault();
var name = document.regForm.FullName.value;
var email = document.regForm.email.value;
var phone = document.regForm.phone.value;
var password = document.regForm.Password.value;
var confirmPassword = document.regForm.ConfirmPassword.value;
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var nameError = emailError = phoneError = passwordError = true;
//Empty name input error message
if (name == "") {
printError("nameError", "Please enter your name")
}
//Empty email input error message
if (email == "") {
printError("emailError", "Please enter a valid email")
}
//Empty phone input error message
if (phone == "") {
printError("phoneError", "Please enter your phone numnber")
}
//Non valid phone number error messsage
if (phone.match(phoneno)) {
return true;
} else {
printError("phoneError", "Please enter a valid phone number")
}
//Empty Password input
if (password == "") {
printError("passwordError", "Please enter a password")
}
//Empty Cofirm Password input
if (confirmPassword == "") {
printError("confirmpassError", "Please confirm your password")
}
//I tried refactoring the passConfirm function and additing it here.
//if (password.match(confirmPassword)) {
// printPass("matchingPassword", "Passwords match")
// document.getElementById("matchingPassword").style.color = "green";
//} else {
// printPass("matchingPassword", "Passwords do no match")
// document.getElementById("matchingPassword").style.color = "red";
//}
};
var passConfirm = function() {  
if (document.getElementById("Password").value ==    document.getElementById("ConfirmPassword").value) {   
document.getElementById("matchingPassword").style.color = "green";   
document.getElementById("matchingPassword").style.fontWeight = "Heavy";   
document.getElementById("matchingPassword").innerHTML = "Passwords match!"  
} else {   
document.getElementById("matchingPassword").style.color = "red";   
document.getElementById("matchingPassword").style.fontWeight = "Heavy";   
document.getElementById("matchingPassword").innerHTML = "Passwords do NOT match!"  
} 
}
fieldset {
width: 420px;
height: 950px;
}
<h1>Hello, please register!</h1>
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm(event)">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<span class="error" id="nameError"></span>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<span class="error" id="emailError"></span>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
<span class="error" id="phoneError"></span>
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
<span class="error" id="passwordError"></span>
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
<span class="error" id="confirmpassError"></span>
</div>
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
Your button disappears because you use InnerHTML method to display the message, which overrides it. Though your logic works after passwords match when you press enter, you lose your button element. It is better to use a separate div or paragraph tag to display your message and keep your button as it is since it's part of the form.
Here is the change you can try
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button></span>
<p id="message"></p>
</fieldset>
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("message").style.color = "green";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
} else {
document.getElementById("message").style.color = "red";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
}
}

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

validate email and display accordingly

I want to check the email validity in Javascript and then show alert box if its invalid and if valid then show the div2. But its not working
Here is javascript:
function _(x){
return document.getElementById(x);
}
function Phase1()
{
myemail = _("email").value;
var reg = /^(([^<>()[\]\\.,;:\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,}))$/;
if (reg.test(designeremail) == false)
{
alert('Invalid Email Address');
}
else
{
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
}
Here is my html:
<form id="myform" onsubmit="return false" >
<div id="phase1">
<label>Email</label><div><input type="text" id="email" name="email" required></div>
<div><button onclick="Phase1()" class="btn"><strong>Next</strong></button></div>
</div>
<div id="phase2">
<label>Name</label><div><input type="text" id="mname" name="myname" required></div>
<div><button onclick="Phase2()" class="btn"><strong>Submit</strong></button></div>
</div>
</form>
but even with wronng email it proceeds and shows the phase2
I think this is js and not php. Btw, it's because probably you're testing on the wrong variable:
if (reg.test(designeremail) == false)
you're testing designeremail, which is different from email from the form which probably you wanted test against to.

JavaScript not validating form on second submit request

I have JavaScript code that will validate a form on the first submit request, but if the user then hits submit again, even though they have not rectified the form errors, the form will not process the validation function and will just submit.
I would like the validation function to be executed every time the user clicks on the submit button.
Thanks for any help, code below.
Martin
<form action="site.url" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname"><span id="inactiveErrorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong></label><br>
<input type="text" name="firstName">
<label for="surname"><br><span id="inactiveErrorSname">Please enter your Surname<br></span>
Surname</label><input type="text" name="lastName">
<label for="email">
<span id="inactiveErrorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong></label>
<input type="text" name="emailAddress">
<input class="button" type="submit" value="Sign up" />
</form>
<script>
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("#");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("inactiveErrorEmail").id = "activeErrorEmail";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
}
</script>
The problem you are facing is created by the fact you are changing the id's of certain elements. The first time you run your code, these statements are succesfully runned:
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
document.getElementById("inactiveErrorEmail").id = "activeErroremail";
The second time however the id's of these elements have changed, resulting in the fact that these statements call upon unexisting elements. This results in a javascript fatal error, with as consequence no return false. The second time your form will thus be submitted as it normally is. The solution to this problem is not changing the id's but changing the class of the error-labels. You can find an example in this fiddle.
HTML:
<form action="#" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname">
<span class="inactive" id="errorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong>
</label><br>
<input type="text" name="firstName"><br><br>
<label for="surname">
<span class="inactive" id="errorSname">Please enter your Surname<br></span>
Surname
</label><br>
<input type="text" name="lastName"><br><br>
<label for="email">
<span class="inactive" id="errorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong>
</label><br>
<input type="text" name="emailAddress"><br><br>
<input class="button" type="submit" value="Sign up" />
</form>
Javascript:
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("#");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("errorFname").className = "active";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("errorSname").className = "active";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("errorEmail").className = "active";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
return false;
}

Categories