Form validation of all entries input Javascript - javascript

I don't quite understand why when I go to the second entry and then to the others(input), my conditions are not taken into account. Did I make a wrong statement in terms of conditions?
In my code, I assigned rules with regex before sending it to the server. Only condition 1 works.
Thank you for your help.
let inputFirstname = document.querySelector('#firstName');
let inputLastname = document.querySelector('#lastName');
let inputEmail = document.querySelector('#email');
let inputAddress = document.querySelector('#address');
let inputCity = document.querySelector('#city');
const regexName = /^[a-zA-Z-\s]+$/;
const regexMail = new RegExp('^[a-zA-Z0-9.-_]+[#]{1}[a-zA-Z0-9.-_]+[.]{1}[a-z]{2,10}$');
const regexNumber = /^[0-9]{5}$/;
const regexAdress = /^(([a-zA-ZÀ-ÿ0-9]+[\s\-]{1}[a-zA-ZÀ-ÿ0-9]+)){1,20}$/;
document.querySelector('#formContact').addEventListener('change', function (e) {
e.preventDefault();
//Test FIRSTNAME //
if (regexName.test(inputFirstname.value)){
inputFirstname.style.border = " #7EEA5E solid 2px";
return true;
}
//Test LASTNAME //
if (regexName.test(inputLastname.value)) {
inputLastname.style.border = " #7EEA5E solid 2px";
return true;
}
//Test EMAIL //
if (regexMail.test(inputEmail.value)) {
inputEmail.style.border = " #7EEA5E solid 2px";
return true;
}
// Test ADRESS //
if (regexAdress.test(inputAddress.value)) {
inputAddress.style.border = " #7EEA5E solid 2px";
return true;
}
// Test CITY //
if (regexName.test(inputCity.value)) {
inputCity.style.border = " #EA6B5E solid 2px";
return true;
}
else {
alert('Good !');
}
});
<form action="/" method="post" class="row gy-4" id="formContact">
<div class=" form-group">
<label for="firstName">Firstname *</label>
<input type="text" class="form-control" placeholder="" name="firstName" id="firstName"
value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="lastName" class="form-label">Lastname *</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder=""
value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="email" class="form-label">Email *</label>
<input type="email" class="form-control" name="email" id="email"
placeholder="mail#example.com" value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="address" class="form-label">Adress *</label>
<input type="text" class="form-control" name="address" id="address"
placeholder="Rue, avenue" value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="city" class="form-label">City *</label>
<input type="text" class="form-control" id="city" name="city" placeholder="" value="">
<span class="error"></span>
</div>
<div class=" form-group my-4 text-center ">
<button class="btn btnSubmit fw-bold btn-secondary" type="submit"
value="">Order</button>
</div>
</form>

The return calls in your checks exit the whole function on first met condition.
I played a bit around and reworked your code.
Your initial problem was, that you had one function, testing everything even if only one thing changed. On top of that, you wanted to return within each check. The return will exit the function entirely when called. Therefore nothing but your first check came through.
You could avoid this by using a switch case and checking depending on your event.target.id which check you want to run.
I introduced a "global" error variable which defaults to true.
After each check this variable is being updated accordingly.
I added a eventListener with Click on your Order Button, which will only send if error = false, otherwise show an alert. Even though I wouldn't use an altert in production code, since it will HALT your entire code, which might cause problems if you're about to work with async calls.
A message for the user to inform him that everything is ready to be sent seems a bit over the top, since you want to color every field as its updated.
let error = true;
const regexName = /^[a-zA-Z-\s]+$/;
const regexMail = new RegExp('^[a-zA-Z0-9.-_]+[#]{1}[a-zA-Z0-9.-_]+[.]{1}[a-z]{2,10}$');
const regexNumber = /^[0-9]{5}$/;
const regexAdress = /^(([a-zA-ZÀ-ÿ0-9]+[\s\-]{1}[a-zA-ZÀ-ÿ0-9]+)){1,20}$/;
document.querySelector('#formContact').addEventListener('change', function (e) {
e.preventDefault();
const borderCode = " #7EEA5E solid 2px";
switch (e.target.id) {
case 'firstName':
if(regexName.test(e.target.value)) {
error = false;
} else {
error = true;
}
break;
case 'lastName':
if(regexName.test(e.target.value)) {
error = false;
} else {
error = true;
}
break;
case 'email':
if(regexMail.test(e.target.value)) {
error = false;
} else {
error = true;
}
break;
case 'address':
if(regexMail.test(e.target.value)) {
error = false;
} else {
error = true;
}
break;
case 'city':
if(regexName.test(e.target.value)) {
error = false;
} else {
error = true;
}
break;
}
if (!error) {
e.target.style.border = borderCode;
}
});
document.querySelector('#submitButton').addEventListener('click', function (e) {
if(error) {
e.preventDefault();
alert('Some Inputs are not valid.');
}
});
<form action="/" method="post" class="row gy-4" id="formContact">
<div class=" form-group">
<label for="firstName">Firstname *</label>
<input type="text" class="form-control" placeholder="" name="firstName" id="firstName"
value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="lastName" class="form-label">Lastname *</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder=""
value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="email" class="form-label">Email *</label>
<input type="email" class="form-control" name="email" id="email"
placeholder="mail#example.com" value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="address" class="form-label">Adress *</label>
<input type="text" class="form-control" name="address" id="address"
placeholder="Rue, avenue" value="">
<span class="error"></span>
</div>
<div class="form-group">
<label for="city" class="form-label">City *</label>
<input type="text" class="form-control" id="city" name="city" placeholder="" value="">
<span class="error"></span>
</div>
<div class=" form-group my-4 text-center ">
<button class="btn btnSubmit fw-bold btn-secondary" type="submit"
id="submitButton" value="">Order</button>
</div>
</form>

Related

Disable submit button when password not match and enable when matched in bootstrap modal

I have a bootstrap modal form for sign up. I want my submit button to be disabled before my password and re-type password are matched. Matched meaning it has to be some input and not empty.
The button should be enabled when matched and disabled again when both fields unmatched again.
I have tried almost all solutions on google and am still stuck for two days.
Here is my form HTML:
<label for="signupModalPassword">Password</label>
<input type="password" class="form-control" name="password" id="signupModalPassword" required="required" onkeyup='check();'>
<p></p>
<label for="signupModalPwCheck">Re-type Password</label>
<input type="password" class="form-control" id="signupModalPwCheck" name="password2" required="required" onkeyup='check();'>
<span id='message'></span>
<p></p>
<div class="form-group">
<button type="submit" id="signupbtn" class="btn btn-lg btn-block login-btn" style="background-color: #fdbf50 !important; color: white !important;">Join Now!</button>
</div>
Here is my script:
if (document.getElementById('signupModalPassword').value ==
document.getElementById('signupModalPwCheck').value) {
document.getElementById('signupbtn').disabled = false;
} else {
document.getElementById('signupbtn').disabled = true;
}
if(document.getElementById('signupModalPassword').value == 0) {
document.getElementById('signupbtn').disabled = true;
} else {
document.getElementById("signupbtn").disabled = false;
}
Please forgive my messy code as I'm very new to coding.
I'll be so grateful if you could help.
example of code:
// validate on first render
check();
function check() {
const signupModalPassword = document.getElementById('signupModalPassword');
const signupModalPwCheck = document.getElementById('signupModalPwCheck');
if (signupModalPassword.value && signupModalPwCheck.value
&& signupModalPassword.value === signupModalPwCheck.value) {
document.getElementById('signupbtn').disabled = false;
}
else {
document.getElementById('signupbtn').disabled = true;
}
}
<label for="signupModalPassword">Password</label>
<input type="password" class="form-control" name="password" id="signupModalPassword" required="required" onkeyup='check();'>
<p></p>
<label for="signupModalPwCheck">Re-type Password</label>
<input type="password" class="form-control" id="signupModalPwCheck" name="password2" required="required" onkeyup='check();'>
<span id='message'></span>
<p></p>
<div class="form-group">
<button type="submit" id="signupbtn" class="btn btn-lg btn-block login-btn" style="background-color: #fdbf50 !important; color: white !important;">Join Now!</button>
</div>

Is there a vanilla JavaScript way to change the value of an input field

What I am trying to achieve is for the value of the id="origin" input field to be updated as you type in the id="pickup" field.
const pickup = document.querySelector('#pickup')
const dropoff = document.querySelector('#dropoff')
const origin = document.querySelector('#origin')
const destination = document.querySelector('#destination')
const submit = document.querySelector('#submitForm')
pickup.addEventListener('input', (e) => {
origin.value = e.target.value
})
.hidden {
opacity: 0;
}
<form>
<div class="form-group">
<label for="pickup">Pickup</label>
<input type="text" class="form-control" id="pickup" aria-describedby="pickupHelp">
<input type="text" class="form-control hidden" id="origin" value="empty">
<small id="pickupHelp" class="form-text text-muted">Enter your pickup location</small>
</div>
<div class="form-group">
<label for="pickup">Drop-off</label>
<input type="text" class="form-control" id="dropoff" aria-describedby="dropoffHelp">
<input type="text" class="form-control hidden" id="destination" value="">
<small id="dropoffHelp" class="form-text text-muted">Enter your drop-off location</small>
</div>
<button type="submit" class="btn btn-primary" id="submitForm">Submit</button>
</form>
I found the solution I was looking for. Sorry for not clearly stating what I wanted to do.
pickup.addEventListener('input', (e) => {
//changed to .defaultValue instead of just .value
origin.defaultValue = e.target.value
})

How to collect all value from HTML form?

I'm currently trying to use jQuery to collect information from a HTML form, but I'm stuck.
Every time I console.log payload its empty and didn't capture the input values.
Questions:
Why is payload empty at the end, after I input values into the form?
how to correct it?
Should I use document.ready for this or window.onload?
Please any help is appreciated.
Here is my last attempt jQuery:
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": []
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
$(".applicantForm input[type=text]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=email]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=tel]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=url]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, "resume.txt");
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="First Name">First Name <span>*</span></label>
<input type="text" name="First Name">
</div>
<div class="input-group">
<label for="Last Name">Last Name <span>*</span></label>
<input type="text" name="Last Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Email">Email <span>*</span></label>
<input type="email" name="Email">
</div>
<div class="input-group">
<label for="Phone">Phone <span>*</span></label>
<input type="tel" name="Phone">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
<div class="input-group">
<label for="LinkedIn Profile">LinkedIn Profile<span>*</span></label>
<input type="url" name="LinkedIn Profile">
</div>
<div class="input-group">
<label for="Website link">Website Link <span>*</span></label>
<input type="url" name="Website link">
</div>
<div class="input-group">
<label for="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?"> In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?<span>*</span></label>
<input type="text" name="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>
Here is the structure of how the payload object should look like in the end:
let payload = {
"fields": [
{ "key" : "candidate_first_name", "value" : "John"},
{ "key" : "candidate_last_name", "value" : "Doe"},
{ "key" : "candidate_email", "value" : "john.doe#gmail.com"},
{ "key" : "candidate_phone", "value" : "1234567890"},
{ "key" : "resume", "value": {
"encoded_data" : "aGVsbG8gd29ybGQ=",
"file_name" : "resume.txt"
}
}
]
};
Note the payload structure is from this link, specifically the "Apply for a Opening" section.
You are running all the code at once (document.ready()), instead you need to run it inside form submit, like $('.applicantForm').on('submit', function(e){}).
Check the updated fiddle
var $ = jQuery;
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": []
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
$('.applicantForm').on('submit', function(e) {
e.preventDefault();
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
$(".applicantForm input[type=text]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=email]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=tel]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=url]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, "resume.txt");
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="First Name">First Name <span>*</span></label>
<input type="text" name="First Name">
</div>
<div class="input-group">
<label for="Last Name">Last Name <span>*</span></label>
<input type="text" name="Last Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Email">Email <span>*</span></label>
<input type="email" name="Email">
</div>
<div class="input-group">
<label for="Phone">Phone <span>*</span></label>
<input type="tel" name="Phone">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
<div class="input-group">
<label for="LinkedIn Profile">LinkedIn Profile<span>*</span></label>
<input type="url" name="LinkedIn Profile">
</div>
<div class="input-group">
<label for="Website link">Website Link <span>*</span></label>
<input type="url" name="Website link">
</div>
<div class="input-group">
<label for="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?"> In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?<span>*</span></label>
<input type="text" name="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>

JavaScript validation: return false not working at time of re Enter Password

My javascript validation code are working..
Javascript: My javascript all field return false are working when re-Enter password javascript return false not working
Re Enter password javascript code not working...
its alert showing ...after alert show form goes submit
return false not working...
[Here is js Fiddle][1]
[1]: https://jsfiddle.net/Ln1cmaps/
**HTML**
<div class="container">
<div class="row main">
<div class="main-login main-center">
<h2>Admin Ragistration</h2>
<form class="" method="post" action="" name="signup" onsubmit="return validate()">
<div class="form-group">
<label for="name" class="cols-sm-2 control-label">Your Name</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter your Name"/>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="cols-sm-2 control-label">Your Email</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
<input type="email" class="form-control" name="email" id="email" placeholder="Enter your Email"/>
</div>
</div>
</div>
<div class="form-group">
<label for="username" class="cols-sm-2 control-label">Username</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter your Username"/>
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="cols-sm-2 control-label">Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="password" id="password" placeholder="Enter your Password"/>
</div>
</div>
</div>
<div class="form-group">
<label for="confirm" class="cols-sm-2 control-label">Confirm Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="confirmpassword" id="confirm" placeholder="Confirm your Password"/>
</div>
</div>
</div>
<div class="form-group ">
<input type="submit" name="submit" value="Register" class="btn btn-primary btn-lg btn-block login-button" />
</div>
</form>
</div>
</div>
</div>
**Javascript validation Code**
function validate() {
var name = document.signup.name.value.length;
var email = document.signup.email.value.length;
var username = document.signup.username.value.length;
var password = document.signup.password.value;
var rpass = document.signup.confirmpassword.value;
var re =(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{8,16}$/);
if(name=="") {
alert("Please Enter Your Name");
document.signup.name.focus();
return false;
}
if(name<3) {
alert("Please Enter Your Correct Name");
document.signup.name.focus();
return false;
}
if(email=="") {
alert("Please Enter email");
document.signup.email.focus();
return false;
}
if(email<3) {
alert("Please Enter Your Correct email");
document.signup.email.focus();
return false;
}
if(username=="") {
alert("Please Enter Username");
document.signup.username.focus();
return false;
}
if(username<5) {
alert("Please Enter Username at least 5 digit");
document.signup.username.focus();
return false;
}
if(password=="") {
alert("Please Enter Your password");
document.signup.password.focus();
return false;
}
if(!re.test(password)) {
alert("Error: Password Must Contain Atleast One Number,One Special Character & One Upper Case");
document.signup.password.focus();
return false;
}
if(rpass =="") {
alert("Please Enter Your Password Again");
document.signup.rpass.focus();
return false;
}
if(rpass != password) {
alert("Password does'nt Matched");
document.signup.rpass.focus();
return false;
}
else {
return true;
}
}
document.signup.rpass.focus();
This is wrong, rpass field is not present. You should write
document.signup.confirmpassword.focus();
https://jsfiddle.net/vineeshmp/Ln1cmaps/1/
Give event.preventDefault(); at starting of your javascript function.
I think you need to change
else {
return true;
}
to a simple
return true;
Your else currently only applies to that last if. You don't need to use an else if you return false on all cases you need to consider.
In other words: if you first check all possibilities for a not valid case, then you can safely return true at the end.
replace your var re with below code : No need to include parentheses
Your code
var re = (/^(?=.[A-Z])(?=.[a-z])(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{8,16}$/);
Updated code
var re = /^(?=.[A-Z])(?=.[a-z])(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{8,16}$/;

Issue With JavaScript / HTML Form Validation

The method validateRegistrationForm is not being called, I have tested this by placing an alert inside and can't figure out why this is the case.
There is other JavaScript to validate other things though I have removed that until this issue is resolved.
The JavaScript itself is being linked to the HTML via script tags inside of the body. I put an alert at the top of the JS to make sure the link is working and it is.
HTML:
<form name="registrationForm" id="registrationForm" action="AddUserDetails">
<div class="form-group">
<label for="firstName">First Name</label>
<span id="firstNameError">*</span>
<input type="text" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName">Second Name</label>
<span id="lastNameError">*</span>
<input type="text" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<span id="phoneNumberError">*</span>
<input type="text" class="form-control" id="phoneNumber">
</div>
<div class="form-group">
<label for="eMail">E-Mail</label>
<span id="eMailError">*</span>
<input type="text" class="form-control" id="eMail">
</div>
<div class="form-group">
<label for="eMailConfirmation">Confirm E-Mail</label>
<span id="eMailConfirmationError">*</span>
<input type="text" class="form-control" id="eMailConfirmation">
</div>
<div class="form-group">
<label for="password">Password</label>
<span id="passwordError">*</span>
<input type="password" class="form-control" id="password">
</div>
</form>
<div class="text-center">
<input type="button" id="submitRegistationForm" value="Submit">
</div>
JavaScript:
var $ = function (id) {
return document.getElementById(id);
}
var validateRegistrationForm = function () {
alert("");
var isValid = true;
//First Name Validation
if ($("firstName").value == "") {
$("firstNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("firstNameError").firstChild.nodeValue = "";
}
//Second Name Validation
if ($("lastName").value == "") {
$("lastNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("lastNameError").firstChild.nodeValue = "";
}
if (isValid) {
$("registrationForm").submit();
}
}
window.onload = function () {
$("submitRegistationForm").onclick = validateRegistrationForm;
}
Redefining $ seems like an awful idea, especially if this is code shared amongst other developers. In either case, why even wait for window.onload? You could just declare your click handler outside of it. Working jsfiddle:
$("submitRegistationForm").onclick = validateRegistrationForm;
https://jsfiddle.net/ou3gLLqe/

Categories