Form validation of email id and password using Javascript - javascript

Code
I cannot understand what is going wrong with this code?
I need to validate emailid and password for the website I am making using Javascript.
The first alert is working properly as well as the alert in else,
only if's lert is not coming.
alert("hi")
const loginForm = document.getElementById("logform");
const loginButton = document.getElementById("logbut");
const emailid = loginForm.emailid.value;
const password = loginForm.password.value;
loginButton.addEventListener("click", function() {
if (emailid === "user#123" && password === "user") {
alert("You have successfully logged in.");
}else{
alert("oh");
}
});

Related

Problems with an infinite loop

I am doing a login for a page, if I enter index.html it has to redirect me to the login, html.
the issue here is that I am getting an infinite loop and I don't know what my syntax error is, I would appreciate your help!
This is where the error is:
sessionStorage.setItem('usuario',false)
var usuario = sessionStorage.getItem(usuario)
var logueate = window.location.replace('login.html')
if (!sessionStorage.getItem('usuario')) {
logueate;}
my login JS code
function validacion(){
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "" ) {
document.getElementById("errores").innerHTML = "Campos invalidos";
} else if (password == "") {
document.getElementById("errores").innerHTML = "Campos invalidos";
}
else { window.location.href="index.html"
Does your login.html is alos executing this code, if yes then it is redirecting again and again to login.html page.

Alert popping up multiple times and submit button only working after second click

I am working on my CS50 Final Project. I am designing a web app:
I am using flask.
This happens in the login/register page.
I am trying to check if the username is already taken( through jsonify) and if the password and the password confirmation are equal using JS.
So basically the problem is:
After loading tha page and filling out the register form nothing happens on the first click on the submit button. On the second click everything works just as it is supposed to: the functions run fine and check for matching passwords and if the username is available and alert if necessary. If I then close the alert window and click the submit button again I get two alerts from the usercheck function.
If do the same thing again 3 alerts then 4 and so on....For some reason the function gets called again and again but I can't figure out where....
Here's the HTML:
<form id='register' action='/register' method="POST" onsubmit="return !!(passwordcheck() & usercheck());" ></form>
Here's the two JS function in a script tag in the same page:
function passwordcheck(){
const password = document.getElementById('password').value;
const passwordc = document.getElementById('passwordc').value;
if (password != passwordc){
alert('Passwords do not match')
return false;
}
}
function usercheck(){
$('document').ready(function(){
$('form').on('submit',function(e){
e.preventDefault();
var username = document.querySelector('#username').value;
$.get('/check?username=' + username, function(r){
if(r == false){
alert('User taken');
$('#username').focus();
}
else{
(document).getElementById('register').submit();
}
} )
})
})
}
And here's the Python code from the application.py file that querys the database for the username:
#app.route("/check", methods=["GET"])
def check():
print(Fore.BLUE + "check function, line 99")
"""Return true if username available, else false, in JSON format"""
username = (request.args.get('username'),)
if username:
c.execute("SELECT username FROM users WHERE username =?", username)
old_user = c.fetchall()
if len(old_user) > 0:
return jsonify(False)
else:
return jsonify(True)
You have defined two handlers for the form submit event:
- the first in the html (onsubmit="return !!(passwordcheck() & usercheck());") is the userCheck function that does not actually make a request
- the second inside the userCheck function ($('form').on('submit',function(e){) that does make a request
So the first time you submit the userCheck function is called, it does not make a request but add a submit event handler to the form. That is why the request is made only after submitting the form a second time.
You should be better off with something like this:
function passwordcheck() {
const password = document.getElementById('password').value;
const passwordc = document.getElementById('passwordc').value;
if (password != passwordc) {
alert('Passwords do not match')
return false;
}
}
function usercheck(handleSuccess, handleError) {
var username = document.querySelector('#username').value;
$.get('/check?username=' + username, function(r) {
if (r == false) {
handleError();
} else {
handleSuccess();
}
})
}
function submit() {
(document).getElementById('register').submit();
}
function handleUserError () {
alert('User taken');
$('#username').focus();
}
$('document').ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
if (!passwordcheck()) {
return;
}
usercheck(submit, handleUserError);
})
})
and without the onsubmit attribute on your form element.

How to instantly redirect the user to a new page via router when the user logs in succesfully(password, username are correct)

Via vue.js I've made a login form with a username and password, and set conditions for them. When the user submits the correct username and password I want to redirect them to a new page vie the vue.js Router. So for example if the user is currently located in "localhost8080/", after a successful login I want to immediately send them to "localhost8080/#/profile"
validate() {
var email = document.getElementById("email").value;
var atSign = email.indexOf("#");
var error = document.getElementById("error");
var mistakes = "";
var hasErrors = false;
if (this.newP != this.password){
mistakes += "Entered password is incorrect. ";
hasErrors = true;
}
if (atSign === -1) {
mistakes += "The email is missing an '#' sign.";
hasErrors = true;
}
// console.log(this.newP.length)
if (hasErrors === true) {
error.innerHTML = mistakes;
return false;
} else {
alert("Login confirmed");
return true;
//I realize it's supposed to be here, but I do not know
//how to write it.
}
}
If You using vue-router, better to use programmatic navigation.
Link: https://router.vuejs.org/guide/essentials/navigation.html
if(loginConfirmed) {
this.$router.push({ path: 'dashboard' });
}

Console says onsubmit function doesn't exist for register form, even though it clearly does

So I have a register form, as thus:
<form name="register" action="" method="POST" onsubmit="register()" autocomplete="off">
...
</form>
And I know that every child of this form is functioning.
Then, below in a <script> tag I have my main function which is called when the above form is submitted. And I know that everything outside of the register function is running. However, when I input random values into each field of my form, and press submit, the console shows that the register() function called in the onsubmit attribute of my form does not exist. I can't seem to find the problem here:
//Global Vars
var firebaseConfig = { ...
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var registerButton = document.querySelector("#registerButton");
//Main Register Function
function register() {
event.preventDefault();
//Locally Global Variables
var fullName = document.forms["register"]["fullName"].value;
var username = document.forms["register"]["username"].value.toLowerCase();
//The MD5 is a way to hash the password, that way the real password is safe and only the hash is used
var password = md5(document.forms["register"]["password"].value);
var serviceProvider = document.forms["register"]["serviceProvider"].value;
//Simple If Statement that adds appropriate email suffix based on Service Provider
if (serviceProvider === "Verizon") {
serviceProvider = "#vtext.com";
} else if (serviceProvider === "ATT") {
serviceProvider = "#txt.att.net";
} else if (serviceProvider === "TMobile") {
serviceProvider = "#tmomail.net";
} else if (serviceProvider === "Sprint") {
serviceProvider = "#messaging.sprintpcs.com";
}
var phoneNumber = document.forms["register"]["phoneNumber"].value + serviceProvider;
var emailAddress = document.forms["register"]["emailAddress"].value;
//Checks The Database If The Username Is Already Taken Or Not
db.collection("Users").where("username", "==", username).get()
.then(function(querySnapshot) {
//Checks Each Individual Result -- If there are no results, than this code will not run
try {
querySnapshot.forEach(function(doc) {
//If any result exists, stop here
if (doc.data()) {
alert("I'm sorry but this username is already taken!! Please Try Another One");
throw "Error";
}
});
} catch (error) {
if (error === "Error") {
return;
}
}
//If not
//Add All Of The User Info To The Database
db.collection("Users").doc(username).set({
fullName: fullName,
username: username,
password: password,
phoneNumber: phoneNumber,
emailAddress: emailAddress,
chatsInvolvedIn: []
})
.then(function() {
//If it succeeds, give user the heads up and then take them to their new homepage
alert("Your account under the username " + username + " has been sucessfully created. You will now be redirected to your homepage.");
//Place Code Underneath to Handle Keeping user Logged In For Present and Future Visits, along with redirecting to a homepage
//Code Goes Here
db.collection("Users").doc(username).get().then(function(doc) {
if (doc.exists) {
localStorage.setItem("loggedIn", JSON.stringify(doc.data()));
}
alert(localStorage.getItem("loggedIn"));
//window.location.replace("index.html");
});
})
.catch(function(error) {
//If it fails, tell user to try again later (we don't care about the error message during production, because it is unlikely after our many tests)
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
})
.catch(function(error) {
//If checking the database originally for duplicate usernames fails, then give the user the same warning as above
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
}
I know that my programming practices above aren't the best. if you could help me out, that would be great, thank you!

Firebase Web app signInWithEmailAndPassword problem

I have a problem with FireBase Web app signInWithEmailAndPassword.
When I press the button Sign In it's showing an only progress bar.
I after that I try to get data from the database and it is working but this signInWithEmailAndPassword isn't working
and here is my code
And If else isn't working becouse when i press the button with "" empty field result is true, not false
I after that i try to get data from the database and it is working but this signInWithEmailAndPassword isnt working
And this is my function for sign in
$("#loginbtn").click(
function(){
var email = $("loginemail").val();
var password = $("loginpassword").val();
if(email != "" && password != ""){
$("#loginprogress").show();
$("#loginbtn").hide();
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
$("#loginerror").show();
$("#loginprogress").hide();
$("#loginbtn").show();
});
}else{
windows.alert("Error");
}
}
);

Categories