Email Signup Form Modal - javascript

I am having trouble when trying to finish a signup form. I've managed to build html code and some js. Can anybody tell me what's missing? Thank You!
<div class="modal" id="email-modal">
<div class="modal-content">
<span class="close-btn">×</span>
<div class="modal-content-left">
<img src="./img/pic1.svg" alt="" id='modal-img' >
</div>
<div class="modal-content-right">
<form action="javascript:Validate(id)" method="GET" class="modal-form" id="form">
<h1>¡Unite a nosotros hoy! Crea tu cuenta completando la información de abajo.</h1>
<div class="form-validation">
<input type="text" class="modal-input" id="name" name="name" placeholder="Ingresá tu nombre">
<p>Error Message</p>
</div>
<div class="form-validation">
<input type="email" class="modal-input" id="email" name="email" placeholder="Ingresá tu mail">
<p>Error Message</p>
</div>
<div class="form-validation">
<input type="password" class="modal-input" id="password" name="password" placeholder="Ingresá tu contraseña">
<p>Error Message</p>
</div>
<div class="form-validation">
<input type="password" class="modal-input" id="password-confirm" name="password" placeholder="Confirmá tu contraseña">
<p>Error Message</p>
</div>
<input type="submit" class="modal-input-btn" value="Sign Up">
<span class="modal-input-login">¿Ya tenes una cuenta? Iniciá sesión acá</span>
</form>
</div>
</div>
</div>
I think it might have something to do with EventListeners. Both the 'name' in checkRequired([name, email, password, passwordConfirm]); and checkLength(name,3,30); appear to be 'deprecated'.
//Modal Items
const modal = document.getElementById('email-modal');
const openBtn = document.getElementById('main__btn');
const closeBtn = document.getElementsByClassName('close-btn')[0];
//Click events
openBtn.addEventListener('click', () => {
modal.style.display = 'block';
});
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (e) => {
if(e.target === modal){
modal.style.display = 'none';
}
});
//Form Validation
const form = document.getElementById('form');
const name = document.getElementById('name');
const email = document.getElementById('email');
const password = document.getElementById('password');
const passwordConfirm = document.getElementById('password-confirm');
//Show error message
function showError(input, message){
const formValidation = input.parentElement;
formValidation.className = 'form-validation error';
const errorMessage = formValidation.querySelector('p');
errorMessage.innerText = message;
}
//Show valid message
function showValid(input){
const formValidation = input.parentElement;
formValidation.className = 'form-validation valid';
}
//Check required fields
function checkRequired(inputArr){
inputArr.forEach(function(input){
if(input.value.trim() === ''){
showError(input,`${getFieldName(input)} is required`);
} else{
showValid(input);
}
})
}
// //Check input lenght
function checkLength(input, min, max){
if(input.value.lenght < min){
showError(input, `${getFieldName(input)} must be at least ${min} characters`);
} else if (input.value.lenght > max) {
showError(input, `${getFieldName(input)} must be less than ${max} characters`);
} else{
showValid(input);
}
}
//Check passwords match
function passwordMatch(input1,input2){
if(input1.value !== input2.value){
showError(input2,'Passwords do not match');
}
}
//Get fieldname
function getFieldName(input){
return input.name.charAt(0).toUpperCase() + input.name.slice(1);
}
//Event Listeners
form.addEventListener('submit', (e) => {
e.preventDefault();
checkRequired([name, email, password, passwordConfirm]);
checkLength(name,3,30);
checkLength(password, 8, 25);
checkLength(passwordConfirm, 8 , 25);
passwordMatch(password, passwordConfirm);
})

Related

Slow JavaScript at the time of form submission

I have a form and I want the submission button to be disabled when the form is submitted
form:
<form id="LoginForm" onsubmit='disableBtn()' asp-controller="Account" asp-action="Login" >
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<input asp-for="Email" id="Email" class="form-control mrg15B" type="email" placeholder="ایمیل">
<span asp-validation-for="Email" class="text-danger"></span>
<input asp-for="Password" id="Password" class="form-control mrg15B" type="password" placeholder="کلـمه عبـور">
<span asp-validation-for="Password" class="text-danger"></span>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="RememberMe" /> #Html.DisplayNameFor(model => model.RememberMe)
</label>
</div>
<button type="submit" id="LoginBtn" class="btn btn-warning btn-block">ورود</button><br>
<br>
</div>
</form>
javascript code:
#section Scripts
{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
function disableBtn() {
let userName = document.getElementById('Email').value;
let password = document.getElementById('Password').value;
if (userName != '' && password != '') {
let btn = document.getElementById('LoginBtn');
btn.disabled = true;
btn.innerHTML = 'please wait ...';
$('#LoginForm').submit();
}
}
</script>
}
And I tested:
$(document).ready(function () {
$('#LoginForm').submit(function () {
let userName = document.getElementById('Email').value;
let password = document.getElementById('Password').value;
if (userName != '' && password != '') {
let btn = document.getElementById('LoginBtn');
btn.disabled = true;
btn.innerHTML = 'please wait ...';
$('#LoginForm').submit();
}
});
});
But it takes a few seconds to reach the btn.innerHTML = 'please wait ...'; line
PS: if the user does not fill in the input, the validators will work and will not allow submission, in which case the button should not be deactivated.
Thankyou
Try to use button click event to submit the form, code like this (remove the onsubmit='disableBtn()' from the form tag):
<script type="text/javascript">
$(function(){
$("#LoginBtn").click(function(){
event.preventDefault(); //prevent the default submit event.
let userName = document.getElementById('Email').value;
let password = document.getElementById('Password').value;
if (userName != '' && password != '') {
let btn = document.getElementById('LoginBtn');
btn.disabled = true;
btn.innerHTML = 'please wait ...';
$('#LoginForm').submit();
}
});
});
</script>
The result as below:

How do I check to see is password matches confirm password before user is allowed to submit the form JS

Basically I have a sign-up form , I want the password and confirm password field to match before the user is allowed to submit the form. I have the password and confirm password matching logic but do not know how to disable user from submitting if they do not match
This is my form in my html
<form action="/register" method="post" novalidate class="mt-4" class="form">
<div class="mb-3">
<label for="username" class="form-label">Company Name*</label>
<input type="text" class="form-control" required id="username" name="username"
placeholder="Facebook Ltd">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address*</label>
<input type="email" class="form-control" required id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="John#gmail.com" name="email">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password*</label>
<input type="password" class="form-control password" required id="password
placeholder="Min 8 Characters" name="password">
</div>
<div class="mb-3">
<label for="confirm-password" class="form-label">Confirm Password*</label>
<input type="password" class="form-control confirm-password" required id="confirm-password" placeholder="Must Match">
<span class="matching-txt mt-1">Not Matching</span>
</div>
<button class="confirm-pwd" type="submit" class="btn mt-3 submit-btn">Sign-up</button>
</form>
This is my logic to compare the password field and confirm password field on keyup
// Password and Confirmed passwords validation
let pwd = document.querySelector('.password');
let confirmPwd = document.querySelector('.confirm-password')
let matchingTxt = document.querySelector('.matching-txt')
let form = document.querySelector('.form')
function comparePwd() {
if (confirmPwd.value) {
if (pwd.value != confirmPwd.value) {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'red'
matchingTxt.innerHTML = 'Not Matching'
e.preventDefault()
} else {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'green'
matchingTxt.innerHTML = 'Matching'
}
} else {
matchingTxt.style.display = 'none'
}
}
confirmPwd.addEventListener('keyup' , () => {
comparePwd()
})
pwd.addEventListener('keyup' , () => {
comparePwd()
})
How do I do it in a way that if passwords do not match user cannot submit the form.
A HTML form element can take use of a special comparison function before submitting by populating its onsubmit attribute. That means the novalidate attribute must not be present.
Your comparePwd() function just needs a little tweak: it needs to return false, in case something is wrong - e.g. the passwords do not match.
So simply change the form to this:
<form action="/register" method="post" onsubmit="return comparePwd()" class="mt-4" class="form">
and the comparison function to this:
function comparePwd() {
if (confirmPwd.value) {
if (pwd.value != confirmPwd.value) {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'red'
matchingTxt.innerHTML = 'Not Matching'
return false
e.preventDefault()
} else {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'green'
matchingTxt.innerHTML = 'Matching'
}
} else {
matchingTxt.style.display = 'none'
}
}
Add this to your code
let submitBtn = document.getElementById("submitBtn");
and add id to the button to make it match:
<button class="confirm-pwd" type="submit" class="btn mt-3 submit-btn" id="submitBtn">Sign-up</button>
This way you can disable the button when the 2 fields do not match
if (pwd.value != confirmPwd.value) {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'red'
matchingTxt.innerHTML = 'Not Matching'
e.preventDefault()
submitBtn.disabled = true
} else {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'green'
matchingTxt.innerHTML = 'Matching'
submotBtn.disabled = false
}
Call your function comparePwd() on click on submit button:
<button onclick="comparePwd()" class="confirm-pwd" type="submit" class="btn mt-3 submit-btn">Sign-up</button>
after adding this onclick action to button, remove the event listeners both
confirmPwd.addEventListener('keyup' , () => {
comparePwd()
})
pwd.addEventListener('keyup' , () => {
comparePwd()
})

Javascript form validation button: Proceed to the next page after form is valid

My form validation works perfectly, but after the form is valid it dosen't proceed to the next page
when i click on the submit button
Here is the html for the code:
<div class="header">
<h2>Create Account</h2>
</div>
<form id="form" class="form" action="Iphone.html" method="post">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Drake" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="applehub#gmail.com" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password</label>
<input type="password" placeholder="Password" id="password"/>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password check</label>
<input type="password" placeholder="Password two" id="password2"/>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<input type="submit" value="Submit" name="">
<p>Have an account? Login.</p>
</form>
</div>
Here is the Javascript, i put the submit button e.preventDefault(); but i can't turn it of when the form is valid:
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if(usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
} else {
setSuccessFor(username);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
} else if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else{
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\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,}))$/.test(email);
}```
You need to manually redirect after you have checked that the validation is correct.
To redirect to another page, you can use:
window.location = "http://www.yoururl.com";
If the application is SPA , use browserhistory.push('/uri');
This is caused by for e.preventDefault();. If this function gets called, the inital action from the form gets 'disabled'.
I think in this situation the best case is to work with flags.
So the solution could look like this:
let is_form_checked = false;
form.addEventListener('submit', e => {
if(!is_form_checked) {
e.preventDefault();
checkInputs();
is_form_checked = true;
//resubmit
}
});

Valid login won't open link

I have pieced together this login form with a Javascript credential validator. For testing verification I have set the login to be Ryan for the username and ryan1234 for the password. When credentials are valid the user should be redirected to Facebook. But, it's not working. The credentials validate properly, but the window.location attribute sends to a broken location?
var modal = document.getElementById('id01');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var attempt = 3;
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "Ryan" && password == "ryan1234") {
alert("Login successfully");
window.location = "https://www.facebook.com/"; // Redirecting to other page.
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
<div id="id01" class="modal">
<form class="modal-content animate" action="action_page.php">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container-modal">
<label><b>Username</b>
</label>
<input type="text" placeholder="Enter Username" name="uname" id="username" required>
<label><b>Password</b>
</label>
<input type="password" placeholder="Enter Password" name="psw" id="password" required>
<button type="submit">Login</button>
<input type="checkbox" checked="checked">Remember me
</div>
<div class="container-modal" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
</div>
window.location = "https://www.facebook.com/"; // Redirecting to other page.
Isn't what you want... It should be window.location.href
Like this:
window.location.href = "https://www.facebook.com/"; // Redirecting to other page.

Form Validation with JavaScript and PHP (Not refresh page on submit)

I am trying to do a form validation with JS that shows feedback as the user types. But of course when submitted the form it's sent using PHP. I already managed to do all of this the only problem I am having now is that when the form is submitted the page refreshes and my "Successfully sent" message cannot be seen. Here is my code and thanks a lot! :D
HTML FORM
<form method="post" id="emailForm" action="?">
<div class="form-group">
<label for="email">Email</label>
<input type="email" placeholder="ejemplo#gmail.com" class="form-control" name="email" id="email"/>
<p class="alert alert-danger errorEmail"></p>
</div>
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" placeholder="María Rodriguez" class="form-control" name="name" id="name"/>
<p class="alert alert-danger errorName"></p>
</div>
<div class="form-group">
<label for="asunto">Asunto</label>
<input type="text" placeholder="Garantía producto" class="form-control" name="asunto" id="asunto" /><span class="badge badgeA"></span>
<p class="alert alert-danger errorAsunto"></p>
</div>
<div class="form-group">
<label for="mensaje">Mensaje</label>
<textarea placeholder="Ingrese su mensaje aquí, trate de ser lo más claro y conciso posible." name="mensaje" id="mensaje" class="form-control" rows="7"></textarea><span class="badge badgeM"></span>
<p class="alert alert-danger errorMensaje"></p>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-success" value="Enviar!"/>
Field to display feedback of submission
<div class="alert alert-success enviado">
</div>
<div class="alert alert-danger noEnviado">
</div>
JavaScript (jQuery)
$(function() {
$(".errorEmail").hide();
$(".errorName").hide();
$(".errorAsunto").hide();
$(".errorMensaje").hide();
$(".enviado").hide();
$(".noEnviado").hide();
var error = false;
$('#email').keyup(function(){
checkEmail();
});
$('#name').keyup(function(){
checkName();
});
$('#asunto').keyup(function(){
checkAsunto();
});
$('#mensaje').keyup(function(){
checkMensaje();
});
function checkEmail() {
var email = $('#email').val();
error = false;
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(email)) {
$('.errorEmail').hide();
}
else {
$('.errorEmail').html("Ingrese un correo electrónico válido.")
$('.errorEmail').show();
error = true;
}
}
function checkName() {
var name = $('#name').val().length;
var minName = 5;
var cantidad = - (name - minName);
error = false;
if (name < 5){
$('.errorName').html("Por favor ingrese su nombre. <b>Mínimo " + cantidad + " caracteres.</b>");
$('.errorName').show();
error = true;
}
else {
$('.errorName').hide();
}
}
function checkAsunto() {
var asunto = $('#asunto').val().length;
var minAsunto = 10;
var cantidad = - (asunto - minAsunto);
error = false;
if (asunto <10){
$('.errorAsunto').html("Por favor ingrese un asunto.<b> Mínimo " + cantidad + " caracteres.</b>");
$('.errorAsunto').show();
error = true;
}
else {
$('.errorAsunto').hide();
}
}
function checkMensaje() {
var email = $('#mensaje').val().length;
var minMensaje = 20;
var cantidad = - (email - minMensaje);
error = false;
if (email < 20){
$('.errorMensaje').html("Por favor ingrese un mensaje. <b> Mínimo " + cantidad + " caracteres. </b>");
$('.errorMensaje').show();
error = true;
}
else {
$('.errorMensaje').hide();
}
}
$('#emailForm').submit( function() {
checkEmail();
checkName();
checkAsunto();
checkMensaje();
if(error === false) {
$('.enviado').html("Mensaje enviado exitosamente");
$('.enviado').fadeIn(500);
$('.noEnviado').fadeOut(500);
return true;
} else {
$('.noEnviado').html("Ups... hubo un problema");
$('.noEnviado').fadeIn(500);
$('.enviado').fadeOut(500);
return false;
}
});
});
PHP
The PHP code is really simple some how it doesn't let me display it here but it just get's the $_POST values on the form and sends them using email();
Thanks guys
Instead of returning true replace it with an Ajax post request to the same script, on success show the message you wish.

Categories

Resources