Email validation not working after rendering html page - javascript

I am trying to do email validation after user type finish their email. However, it is not indicating that the email is valid or not. I place the javascript at the top to let it run while rendering but it doesn't work either. The code below is the screen for registration using javascript. This is rendered using nodejs. Is it due to the position of code or am I missing something?
RegisterScreen.js
const RegisterScreen = {
render: () =>
`
<script type="text/javascript">
const email = document.getElementById("email")
email.addEventListener('input',()=>{
const emailBox = document.querySelector('.emailBox')
const emailText = document.querySelector('.emailText')
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/
if(email.value.match(emailPattern)){
emailBox.classList.add('valid')
emailBox.classList.remove('invalid')
emailText.innerHTML = "Your Email Address in Valid"
}else{
emailBox.classList.add('invalid')
emailBox.classList.remove('valid')
emailText.innerHTML = "Must be a valid email address."
}
})
</script>
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name"
name="name"
id="name"
required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email"
name="email"
id="email"
required
/>
<span class="emailText"></span>
</li>
<li>
<label for="password">Password</label>
<input type="password"
id="password"
name="password"
required
/>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password"
id="re-password"
name="re-password"
required
/>
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
</div>`,
}
export default RegisterScreen

Your javascript is executing on HTML elements that don't yet exist. Load the javascript up after the page loads:
<script type="text/javascript">
window.onload = function() {
const email = document.getElementById("email")
email.addEventListener('blur',()=>{
const emailBox = document.querySelector('.emailBox')
const emailText = document.querySelector('.emailText')
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/
if(email.value.match(emailPattern)){
emailBox.classList.add('valid')
emailBox.classList.remove('invalid')
emailText.innerHTML = "Your Email Address in Valid"
}else{
emailBox.classList.add('invalid')
emailBox.classList.remove('valid')
emailText.innerHTML = "Must be a valid email address."
}
})
}
</script>

Related

How to check email input from HTML button in Javascript

The outcome I want:
Click the button (div class button)
Check what is inputted (div class email)
If it isn't an email, return an error that it isn't an email.
<div class="Email">
<input type="text" name="" class="em" placeholder="Email Address">
</div>
<div class="button" > <h2 class="re"> Request Access </h2> </div>
</div>
I don't know where to start from JavaScript code. Any tips will help.
Use regex to validate things like emails, passwords, usernames, etc. It's really powerful and can do a ton.
Solution:
<form class="email">
<input type="email" class="emailInput" placeholder="Email Address" />
<button type="submit">Request Access</button>
<p id="error" style="color: red; display: none">Please enter a valid email</p>
</form>
<script>
const email = document.querySelector('.emailInput');
const submit = document.querySelector('button');
const error = document.querySelector('#error');
const showError = () => {
error.style.display = 'block';
};
submit.addEventListener('click', (e) => {
e.preventDefault();
if (!email.value.match(/[^# \t\r\n]+#[^# \t\r\n]+\.[^# \t\r\n]+/)) {
return showError();
}
console.log('success');
});
</script>

Uncaught ReferenceError function not defined for password and repassword

I have this error message below despite setting the javascript in the html. The code below is my html code for registration but none of the javascript function or event listener are working. I am still learning about javascript and html so please advice on what I did wrong.
Error message
Uncaught ReferenceError: matchTest is not defined at HTMLInputElement.onkeyup
Register page
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name"
name="name"
id="name"
required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email"
name="email"
id="email"
required
/>
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password"
id="password"
name="password"
class="password"
required
/>
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password"
id="re-password"
name="re-password"
class="re-password"
onkeyup="matchTest()"
required
/>
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
<script type="text/javascript">
window.onload = function() {
let email = document.getElementById("email")
let password = document.getElementById("password")
email.addEventListener('input',()=>{
let emailBox = document.querySelector('.emailBox')
let emailText = document.querySelector('.emailText')
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/
if(email.value.match(emailPattern)){
emailBox.classList.add('valid')
emailBox.classList.remove('invalid')
emailText.innerHTML = "Your Email Address in Valid"
}else{
emailBox.classList.add('invalid')
emailBox.classList.remove('valid')
emailText.innerHTML = "Must be a valid email address."
}
})
password.addEventListener('input',()=>{
let passBox = document.querySelector('.passBox');
let passText = document.querySelector('.passText');
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if(password.value.match(passPattern)){
passBox.classList.add('valid');
passBox.classList.remove('invalid');
passText.innerHTML = "Your Password in Valid";
}else{
passBox.classList.add('invalid');
passBox.classList.remove('valid');
passText.innerHTML = "Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
})
function matchTest(){
let password = document.querySelector('password').value
let confirmPassword = document.querySelector('re-password').value
if(password != confirmPassword)
alert("Password don't match. Please try again.")
return false
}
else if(password == confirmPassword){
alert("Password match")
}
}
}
</script>
</div>
You need to change following things:
It is recommended to define addEventListener in JS not inline
repeatPassword.addEventListener("keyup", (e) => { matchTest(); });
Since you've defined the variable password, so it would be consistent to add repeatPassword also and get its value as password.value and reapatPassword.value in matchTest.
It is recommended to use === instead of ==.
I've used console.log in place of alert. Since you are checking for password equality then it's annoying to get alert after every key press.
window.onload = function() {
let email = document.getElementById("email");
let password = document.getElementById("password");
let repeatPassword = document.getElementById("re-password");
email.addEventListener("input", () => {
let emailBox = document.querySelector(".emailBox");
let emailText = document.querySelector(".emailText");
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/;
if (email.value.match(emailPattern)) {
emailBox.classList.add("valid");
emailBox.classList.remove("invalid");
emailText.innerHTML = "Your Email Address in Valid";
} else {
emailBox.classList.add("invalid");
emailBox.classList.remove("valid");
emailText.innerHTML = "Must be a valid email address.";
}
});
password.addEventListener("input", () => {
let passBox = document.querySelector(".passBox");
let passText = document.querySelector(".passText");
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if (password.value.match(passPattern)) {
passBox.classList.add("valid");
passBox.classList.remove("invalid");
passText.innerHTML = "Your Password in Valid";
} else {
passBox.classList.add("invalid");
passBox.classList.remove("valid");
passText.innerHTML =
"Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
});
function matchTest() {
let pass = password.value;
let confirmPass = repeatPassword.value;
if (pass !== confirmPass) {
console.log("Password don't match. Please try again.");
return false;
} else {
console.log("Password match");
}
}
repeatPassword.addEventListener("keyup", (e) => {
matchTest();
});
};
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name" name="name" id="name" required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email" name="email" id="email" required />
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password" id="password" name="password" class="password" required />
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password" id="re-password" name="re-password" class="re-password" required />
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
</div>

Retrieving Data from Local Storage - key value pairs apparently don't match (error)

I am trying to make a functional login and registration pages (I know that in real life I need to store the login info in a database but for now I would like to see my pages "working"). I created two pages with forms one for registration and one for login. I also have two JS files one for locally storing input values (registerDetails.js) and one for retrieving those values during login (login.js).
Storing the information is not a problem, however, when I try to log in with the information I have just inputted and know it's correct it still throws an "Error" at me to say that password and username don't match even though I know they do match.
SOLUTION IN THE COMMENTS - MIX UP OF VARIABLES
I even tried to error handle if there is a problem with browser compatibility, still to no avail.
This is HTML for register.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Register or <a class="login-link" href="login.html">Login</a>
</legend>
<p>All fileds marked with * are required.</p>
</div>
<hr />
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username"><span class="asterisk">*</span> Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Any letters or numbers without spaces"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email"><span class="asterisk">*</span> E-mail</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Enter your email here" class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password"><span class="asterisk">*</span> Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password of atleast 4 characters"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password -->
<label class="control-label" for="password_confirm"><span class="asterisk">*</span> Confirm Password</label>
<div class="controls">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Please confirm password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button type="submit" id="register" class="btn btn-success" onClick="store()">
Register
</button>
</div>
</div>
</fieldset>
</form>
Here is my HTML for login.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Login or <a class="login-link" href="register.html">Register</a>
</legend>
</div>
<hr />
<div class="control-group">
<!-- Username or Email-->
<label class="control-label" for="username">Username or Email</label>
<div class="controls">
<input type="text" id="usernameEmail" name="usernameEmail" placeholder="Enter your email or username"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="passwordLogin" name="password" placeholder="Enter your password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" type="submit" onclick="check()">Login</button>
</div>
</div>
</fieldset>
</form>
My registration JS works fine, the browser prompts me to save credentials for later use...
Which is here:
// Getting details from the registration form to later store their values
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
// Locally storing input value from register-form
function store() {
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
My login page, however, throws the ERROR alert, even when I know for sure that the username and password match.
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
// var storedEmail = localStorage.getItem('email');
var storedPassword = localStorage.getItem('password');
// entered data from the login-form
var userNameLogin = document.getElementById('usernameEmail');
var userPwLogin = document.getElementById('passwordLogin');
// check if stored data from register-form is equal to data from login form
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
alert('You are loged in.');
} else {
alert('ERROR.');
}
}
I have spent a few hours trying to rewrite the code to maybe see some typos or mistakes but I cannot find where I am going wrong! If anyone could help out as to show the reason why it does not match the username and password would be great.
It should alert me "You are logged in."
Thanks!
You have a typo
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
^^Here
}
Should be this instead
if (userNameLogin.value == storedName && userPwLogin.value == storedPassword ) {
}
By the way, your code will only log in with username (and not email) as it is. Don't forget to compare the email too.
Variables that are meant to store your elements at register page(userName, userEmail, etc.) might be null when store() is called.
I would suggest to get those inside the function:
function store() {
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
But the solution lies in this line:
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin)
In your case storedPassword doesn't have "value" and userPwLogin does, since userPwLogin is the element on your form
Your code isn't working right because you've mixed up your local storage variable with your input elements. This line:
if (userNameLogin.value === storedName && storedPassword.value === userPwLogin) {
it should be:
if (userNameLogin.value === storedName && userPwLogin.value === storedPassword) {

Upload a picture in signup with Firebase

I am using Firebase.auth to sign up users on my website.
In order to get more informations from them, I also create a Firestore Document that stores more informations. Here is my code:
HTML
<div class="col-md-6">
<div class="row justify-content-center align-items-center h-md-100vh">
<div class="col-10 my-5 my-md-0">
<h2 class="h4 font-weight-bold">Signup To Become A Player</h2>
<form id="player-login-form">
<div class="form-group">
<input type="text" id="player-signup-firstname" name="player_signup[firstname]" required="required" placeholder="What's your firstname?" class="form-control">
<div class="invalid-feedback mt-0"></div>
</div>
<div class="form-group">
<input type="text" id="player-signup-lastname" name="player_signup[lastname]" required="required" placeholder="What's your lastname" class="form-control">
<div class="invalid-feedback mt-0"></div>
</div>
<div class="form-group">
<input type="email" id="player-login-email" name="player_signup[email]" required="required" placeholder="What's your email?" class="form-control">
<div class="invalid-feedback mt-0"></div>
<small id="emailHelp" class="form-text text-muted"></small>
</div>
<div class="form-group ">
<input type="password" id="player-login-password" name="player_signup[password]" required="required" placeholder="Set a password" class="form-control">
<div class="invalid-feedback mt-0"></div>
</div>
<div class="form-group ">
<input type="file" accept="image/*" capture="camera" id="cameraInput">
</div>
<button type="submit" class="btn btn-primary" id="player-signup-button">Create account</button>
</form>
</div>
</div>
</div>
And JS
// The sign up variables and constants
const signUpBtn = document.querySelector('#player-signup-button');
// Sign up function
signUpBtn.addEventListener("click", (e) => {
e.preventDefault(); // avoid the page to refresh when we click signup
// get user info from the id of the input
const loginForm = document.querySelector('#player-login-form');
const firstname = loginForm['player-signup-firstname'].value;
const lastname = loginForm['player-signup-lastname'].value;
const email = loginForm['player-login-email'].value;
const password = loginForm['player-login-password'].value;
// Upload picture part
var refname = 'photos/' + firstname + lastname;
let storageRef = firebase.storage().ref(refname);
let fileUpload = document.getElementById("cameraInput")
fileUpload.addEventListener('change', function(evt) {
console.log("Is code going here?");
let firstFile = evt.target.files[0] // upload the first file only
let uploadTask = storageRef.put(firstFile).then(function(fileSnapshot) {
firebase.firestore().collection('players').add({
firstname: firstname,
lastname: lastname,
email: email,
profilepic: fileSnapshot.ref.getDownloadURL()
});
})
});
auth.createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
M.toast({html:error.message});
}).then( cred => {
loginForm.reset();
});
});
**My question: ** I have issues for the image uploading part. It looks like the code inside fileUpload.addEventListener is not read by the interpreter.
Do you have any ideas where is the issue?
You need to put this callback registration outside the click handler:
document.getElementById("cameraInput").addEventListener('change', function(evt) {...});
Right now your code says "after the user submits the form, start listening for them to browse for a picture" when what you really want is "when the page loads, start listening for the user to browse for a picture. Afterwards, when they submit the form read the selected picture file and send it to the server."

JavaScript form validation not working as intended

Good morning,
I'm working on some simple form validation. Whenever I submit my form, the error message appears, but I can repeatedly spam the button for numerous error messages. Is there a way I can change this to only show the error message once? I've also noticed that even if I populate both fields it will still flash quickly in my console with the error log but not show the error.
Can anyone tell me what I'm doing wrong here?
var uname = document.forms['signIn']['userame'].value;
var pword = document.forms['signIn']['password'].value;
function validateMe (e) {
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe();">Sign In</button>
</div>
</div>
</form>
Fiddle
You must be clearing the contents of your container to avoid duplication of elements. Below are few things to note:
You were trying to get userame instead of username in your fiddle. May be spelling mistake.
Keep input type=submit instead of button
Pass the event to your validateMe function to prevent the default action of post.
Move the variables within the function to get the actual value all the time
function validateMe(e) {
e.preventDefault();
var uname = document.forms['signIn']['username'].value;
var pword = document.forms['signIn']['password'].value;
var container = document.getElementById('error-container');
container.innerHTML = ''; //Clear the contents instead of repeating it
if (uname.length < 1 || pword.length < 1) {
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<input value="Sign In" class="button clear right-floater" type="submit" onclick="validateMe(event);" />
</div>
</div>
</form>
Updated Fiddle
Edit - if condition was failing and have updated it accordingly
this is full work code
var uname = "";
var pword = "";
function validateMe(e) {
e.preventDefault();
uname = document.forms['signIn']['username'].value;
pword = document.forms['signIn']['password'].value;
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
return true;
}
<form id="signIn">
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe(event);">Sign In</button>
</div>
</div>
</form>

Categories