On click function is not defined and i dont know why - javascript

I have to validate an email and a phone. It is not necessary that both are mandatory, just one is enough.
When i click my button, the code error is that handleValidation is not defined, but i do not why. Even the console don't print the console.log.
Here the HTML:
<form class="form-group p-4">
<div class="row">
<div class="col-12 col-md-6 d-flex flex-column">
<input type="text" class="form-control rounded-0 p-3 m-1" id="name" required
placeholder="NOMBRE Y APELLIDO">
<input type="email" class="form-control rounded-0 p-3 m-1" id="email" placeholder="E-MAIL">
<input type="tel" class="form-control rounded-0 p-3 m-1" id="phone" placeholder="TELÉFONO">
</div>
<div class="col-12 col-md-6 d-flex flex-column">
<textarea id="message" class="form-control rounded-0 h-100 p-3 m-1" required
placeholder="DEJANOS TU MENSAJE"></textarea>
</div>
</div>
<div class="row">
<div class="col-12 col-md-3 d-flex flex-column float-right align-items-end">
<button onclick="handleValidation()" id="send-btn"
class="main-btn btn btn-primary col-12 rounded-0 p-2 mt-3">ENVIAR</button>
</div>
</div>
</form>
and here the JS:
let email = document.querySelector("#email");
let tel = document.querySelector("#phone");
const emailVal = () => {
if (!(/\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)/.test(email))) {
console.log("bad")
return false;
}
console.log("good")
return true;
}
const telVal = () => {
if (!(/^\d{9}$/.test(tel))) {
console.log("bad")
return false;
}
console.log("good");
return true;
}
const handleValidation = () => {
if (emailVal() === true || telVal() === true) {
alert("tu consulta fue enviada satisfactoriamente");
} else {
alert("el email y/o el teléfono son necesarios para contactarte");
}
}

Set an event listener in the script instead of onclick attribute
You do not get the values of the inputs but the inputs
Input values should be grabbed into the validations functions, not outside
Your email regex doesn't seems to work (I didn't check the phone number one)
If you correct all this problems, your script should look like that :
const emailVal = () => {
let email = document.querySelector("#email").value;
if (!(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email))) {
console.log("bad email")
return false;
}
console.log("good")
return true;
}
const telVal = () => {
let tel = document.querySelector("#phone").value;
if (!(/^\d{9}$/.test(tel))) {
console.log("bad tel")
return false;
}
console.log("good");
return true;
}
const handleValidation = () => {
if (emailVal() || telVal()) {
alert("tu consulta fue enviada satisfactoriamente");
} else {
alert("el email y/o el teléfono son necesarios para contactarte");
}
}
document.getElementById('send-btn').addEventListener('click', handleValidation);
You will also have to remove your button onclick attribute of course.
Source for email validation regex : https://www.w3resource.com/javascript/form/email-validation.php

I checked your code in jsfiddle. I receive very time "el email y/o el teléfono son necesarios para contactarte". So code is correct to some extends. I suggest add the JSSript after the html and vice versa. I'm mixing this all time up.

Related

Email Signup Form Modal

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);
})

Subscription button with data validation

What the script does is hide the input element and show the "thanks message".
But prior to this I need it to validate if input emailfield is validated, and show the "thanks message" only if that happens.
Thanks!
var nextStep = document.querySelector('#nextStep');
nextStep.addEventListener('click', function(e) {
e.preventDefault()
// Hide first view
document.getElementById('my_form').style.display = 'none';
// Show thank you message element
document.getElementById('thank_you').style.display = 'block';
});
<form class="row row-cols-lg-auto g-2 align-items-center justify-content-end">
<div class="col-12" id="my_form">
<input id="emailfield" type="email" class="form-control" placeholder="Ingresa tu Email" required="required">
</div>
<div class="col-12" id="thank_you" style="display: none;">
Gracias por subscribirse!
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary-soft m-0" name="subscribirse" id="nextStep">Subscribirse</button>
</div>
</form>
var nextStep = document.querySelector('#nextStep');
nextStep.addEventListener('click', function (e) {
e.preventDefault()
let inputEmail = document.querySelector('#emailfield')
if (/.*\#.*\..*/.test(inputEmail.value)) {
// validation passed
// Hide first view
document.getElementById('my_form').style.display = 'none';
// Show thank you message element
document.getElementById('thank_you').style.display = 'block';
} else {
// validation not passed
}
});
Instead of this regexp you can use any that you want

Cannot read property 'stripeTokenHandler' of undefined vuejs component

I am building a payment form with vuejs, it included stripe js.
This is my card elements:
<!-- CARD form -->
<label class="mt-5 font-20px"> Tarjeta </label>
<div class="mt-4"> Número </div>
<div class="row mt-2">
<div class="col-md-12">
<div id="card-number-element" class="form-control rounded-pill" placeholder="**** **** **** ****"> </div>
</div>
</div>
<div class="row">
<div class= "col-md-6 mt-3">
<span> Nombre de la Tarjeta </span></br>
<input type="input" id="card-name-element" class="form-control rounded-pill" placeholder ="Juan Pérez"> </input>
</div>
<div class= "col-md-3 col-6 mt-3">
<span> Expiración </span></br>
<div id="card-expiry-element" class="form-control rounded-pill" placeholder ="MM / YY"> </div>
</div>
<div class= "col-md-3 col-6 mt-3">
<span> CCV </span></br>
<div id="card-cvc-element" class="form-control rounded-pill" placeholder ="***"> </div>
</div>
</div>
<div class="row mt-3">
<div id="card-error text-danger"></div>
<div id="card-success">
Your Stripe token is <span class="token text-success"></span>
</div>
</div>
I initialized stripe elements in mounted function:
initStripeElements(){
cardNumberElement = elements.create('cardNumber', { placeholder: '**** **** **** ****', });
cardNumberElement.mount('#card-number-element');
var cardExpiryElement = elements.create('cardExpiry', { placeholder: 'MM / YY', });
cardExpiryElement.mount('#card-expiry-element');
var cardCvcElement = elements.create('cardCvc', { placeholder: '***', });
cardCvcElement.mount('#card-cvc-element');
},
mounted() {
this.initStripeElements();
}
Everything work fine and the stripe card token can be retrieved and returned.
After that I invoke: this.stripeTokenHandler(result.token.id); to send token and data to server
submitForm(e) {
e.preventDefault();
this.submitted = true;
if (this.formInvalid()) {
return;
}
var options = {
name: document.getElementById('card-name-element').value,
};
stripe.createToken(cardNumberElement, options).then(function(result) {
var successElement = document.querySelector('.card-success');
var errorElement = document.querySelector('.card-error');
if (result.token) {
successElement.querySelector('.token').textContent = result.token.id;
this.stripeTokenHandler(result.token.id);
} else if (result.error) {
errorElement.textContent = result.error.message;
}
console.log(this)
});
if (this.cardError) {
return;
}
// this.nextStep();
},
This calling never work as it always show the error:
Finaliza.vue:415 Uncaught (in promise) TypeError: Cannot read property 'stripeTokenHandler' of undefined
Can you please help, what am I wrong here?
By somehow this variable is become undefined inside the stripe scope. So I can solve issue by saving this variable outside the stripe callback.
var context = this;
stripe.createToken(cardNumberElement, options).then(function(result) {
var successElement = document.querySelector('.card-success');
var errorElement = document.querySelector('.card-error');
if (result.token) {
successElement.querySelector('.token').textContent = result.token.id;
context.stripeTokenHandler(result.token.id);
} else if (result.error) {
errorElement.textContent = result.error.message;
}
});

Test if a function with multiple if/else blocks return true or false in javascript

I'm not sure if this question has been asked before or not,
I'm trying to make a validation form using Javascript.
My question is: is there any way to test if my functions validateEmailLogin() and validatePsswordLogin() returns true or false in all if/else blocks, so I can test in the function isValide() whether the two functions return true or false and do a treatment.
Ps: it's a bit messy code and any suggestions to reduce it and make it cleaner are welcome.
Here's my html and js code :
function validateEmailLogin() {
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
} else {
emailMessagePatern.classList.add("d-none");
}
}
function validatePsswordLogin() {
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
}
function isValide() {
if (validateEmailLogin() && validatePsswordLogin()) {
window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
return false;
} else {
alert('check your credentials');
}
}
My HTML
form name="loginForm" method="POST">
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small></p>
</div>
<button onclick="return isValide()" type="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
</form>
I like your code!
The message holders = nice!
I've made some modifications:
added valid flag initialized as true, set to false when not valid, and returned from both validate functions
changed isValide to valide and removed the return
removed the <form>
removed type=submit from button
button just calls valide - whatever is needed to be done - from there
commented out change of href for demonstration - uncomment when ready, actually, use location.replace(URL); instead of window.location.href = URL;
Notes:
your URL is a local file...
the email validator function is not complete (x#.com#.com - passes, for example...)
function validateEmailLogin() {
var valid=true;
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
valid=false;
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
valid=false;
} else {
emailMessagePatern.classList.add("d-none");
}
return valid;
}
function validatePsswordLogin() {
var valid=true;
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
valid=false;
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
return valid;
}
function valide() {
if (validateEmailLogin() && validatePsswordLogin()) {
alert("valid");
// window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
} else {
alert('check your credentials');
}
}
.d-none {
display:none;
}
<!-- form name="loginForm" method="POST" -->
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small>
</p>
</div>
<button onclick="valide()" xtype="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
<!-- /form -->

Onclick html call for JavaScript function not working in Safari

I am trying to call a function in my javascript file from an onclick event in html. This code works perfectly in Google Chrome but does not work in Safari as it redirects to the same page and empties the form, without redirecting to the home page of my website.
Here is my HTML code:
<!-- Login or subscribe form-->
<div class="py-5">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card text-white p-5 bg-primary signUpBoxStyle">
<div class="card-body">
<h1 class="mb-4">Effettua il login o iscriviti</h1>
<form>
<div class="form-group"> <label>Indirizzo email</label>
<input type="email" class="form-control" placeholder="Inserisci email" id="email"> </div>
<div class="form-group"> <label>Password</label>
<input type="password" class="form-control" placeholder="Password" id="password"> </div>
<input type="button" class="btn btn-light text-primary btn-sm" value="Accedi" onclick="loginFunction()">
<input type="button" class="btn btn-light text-primary btn-sm" value="Crea un Account" onclick="signupFunction()"> </form>
</div>
</div>
</div>
</div>
</div>
</div>
And this is my JavaScript
function loginFunction() {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
})
};
You might need to tell the browser not to carry out the default behavior of that element via preventDefault(). This SO answer give a little more detail.
Having an if statement to check the attribute is not that scalable but it may be possible that you pass the function call as a parameter.
let buttons = document.querySelectorAll('input[type=button]')
buttons.forEach(button => {
button.addEventListener('click', e => {
let func = e.target.getAttribute('data-call')
if (func === 'login') {
loginFunction()
} else if (func === 'signup') {
signupFunction()
}
})
})
let loginFunction = () => {
console.log('loginFunction')
}
let signupFunction = () => {
console.log('signupFunction')
}
<form>
<input type="button" value="Accedi" data-call="login">
<input type="button" value="Crea un Account" data-call="signup">
</form>

Categories

Resources