Local and Session Storage for Login and Registration

Asked

Viewed 860 times

0

I have tried to do over two weeks in javascript and Html5, a registration and login form. After several unsuccessful attempts, I’ve come to ask for your help in solving this headache :(

Here’s the code I’ve already developed:

<script>
    document.write(outstate(isative()));
</script>

    <form>
        <input type="email" id="user" onblur="verlogin()" required>
        <input type="password" id="pass" onblur="verlogin()" required>
        <span id="mess"></span>
        <button  type="submit" disabled id="login" onclick="login();">LOGIN</button>
    </form>

        <input type="email" id="usermail" onblur="veruser();ch();" required>
        <span id="veruser"></span>
        <button style="text-decoration: none!important;display: none;" id="uservalue" value="0"></button>
        <input type="password" id="password" onblur="verpass();ch();" required>
        <input type="password" id="confirmpassword" onblur="verpass();ch();" required>
        <span id="verpass"></span>
        <button style="text-decoration: none!important;display: none;" id="passvalue" value="0"></button>
        <input type="text" id="morada" required>
        <input type="number" maxlength="9" id="nif"  required>
        <button type="submit" id="registar" onclick="registar();">REGISTAR</button>

</body>

In Javascript a friend of mine helped me develop this, but it doesn’t work correctly:

   function() {
        var User = function User(mail, password, morada, nif) {
            this.mail = mail;
            this.password = password;
            this.morada = morada;
            this.nif = nif;
        }

        User.prototype = {
            login: function () {
                return this.mail + " " + this.password;
            },
            allData: function () {
                return this.mail + " " + this.password + " " + this.morada + " " + this.nif;
            }
        };


        var armazenamento = [];

        function registar() {
            var usermail = document.getElementById('email').value;
            var userpassword = document.getElementById('password').value;
            var usermorada = document.getElementById('morada').value;
            var usernif = document.getElementById('nif').value;
            localStorage.setItem(usermail,userpassword + '|'+usermorada);
            sessionStorage.setItem(usermail,'ativo');
            var obj = new User(usermail, userpassword, usermorada, usernif);
            armazenamento.push(obj);
        };


        function visualizacao() {
            var text = " ", saida = 0 ;
            for (var i = 0; i<armazenamento.length ; i++){
                text += armazenamento[i].allData();
                text += "<br>";
            }
            saida= document.getElementById ("saida");
            saida.innerHTML = text;
        };

        window.onload = function (){
            var btnregisto = document.getElementById ("registo");
            btn1.addEventListener("click",registar);

            var btnver = document.getElementById ("visualizar");
            btn2.addEventListener("click",visualizacao);


        }


    })();

Second Javascript code I have:

window.onload=function(){
    if(sessionStorage.length==0){
        var key='';
        for(var i=0;i<localStorage.length;i++){
            key = localStorage.key(i);
            sessionStorage.setItem(key,'');
        }
    }
}

function verlogin(){
    var nome=document.getElementById('user').value;
    var pass=document.getElementById('pass').value;
    document.getElementById('mess').innerHTML = '';
    var key='';
    var val='';
    if(localStorage.length!=0){
        for(var i=0;i<localStorage.length;i++){
            key = localStorage.key(i);
            val = localStorage.getItem(key);
            if(nome!='' || pass!=''){
                if(nome==key){
                    if(val.substr(0, val.indexOf('|'))==pass) {
                        document.getElementById('mess').style.color='green';
                        document.getElementById('mess').innerHTML = 'Válido';
                        document.getElementById("login").disabled = false;

                    }else{
                        document.getElementById("login").disabled = true;

                        document.getElementById('mess').style.color='red';
                        document.getElementById('mess').innerHTML = 'Utilizador ou Palavra Pass Errados';
                    }
                }else{
                    document.getElementById("login").disabled = true;
                    document.getElementById('mess').style.color='red';
                    document.getElementById('mess').innerHTML = 'Utilizador ou Palavra Pass Errados';
                }
            }else{
                document.getElementById('mess').innerHTML = '';

            }
        }
    }else{
        document.getElementById("login").disabled = true;
        document.getElementById('mess').style.color='red';
        document.getElementById('mess').innerHTML = 'crie uma conta';
    }

}

function login(){
    var nome=document.getElementById('user').value;

    sessionStorage.setItem(nome,'ativo');
    window.location.href='login.html';
}

function veruser(){
    var nome=document.getElementById('usermail').value;
    document.getElementById('uservalue').value = 0;
    var key='';
    if(localStorage.length!=0) {
        for (var i = 0; i < localStorage.length; i++) {
            key = localStorage.key(i);
            if (nome != '') {
                if (nome == key) {
                    document.getElementById('uservalue').value = 0;
                    document.getElementById('veruser').style.color = 'red';
                    document.getElementById('veruser').innerHTML = 'Utilizador Utilizado';
                } else {
                    document.getElementById('uservalue').value = 1;

                    document.getElementById('veruser').style.color = 'green';
                    document.getElementById('veruser').innerHTML = 'Válido';

                }
            } else {
                document.getElementById('veruser').innerHTML = '';

            }
        }
    }else{
        document.getElementById('uservalue').value = 1;

        document.getElementById('veruser').style.color = 'green';
        document.getElementById('veruser').innerHTML = 'Válido';
    }
}
function ch(){
    var verp = document.getElementById('passvalue').value;
    var veru = document.getElementById('uservalue').value;
    document.getElementById("login").disabled = true;

    if(verp==1 && veru==1){
        document.getElementById("registar").disabled = false;
    }else{
        document.getElementById("login").disabled = true;

    }

}
function verpass(){
    var pass1=document.getElementById('password').value;
    var pass2=document.getElementById('confirmpassword').value;
    document.getElementById('passvalue').value = 0;
    if(pass1!='' || pass2!=''){
        if(pass1!=pass2){
            document.getElementById('passvalue').value = 0;
            document.getElementById('verpass').style.color='red';
            document.getElementById('verpass').innerHTML = 'Password não Corresponde';
        }else{
            document.getElementById('passvalue').value = 1;
            document.getElementById('verpass').style.color='green';
            document.getElementById('verpass').innerHTML = 'Válido';
        }
    }else{
        document.getElementById('veruser').innerHTML = '';

    }
}

function registar(){
    var verp = document.getElementById('passvalue').value;
    var veru = document.getElementById('uservalue').value;
    var user=document.getElementById('usermail').value;
    var pass=document.getElementById('password').value;
    var mor=document.getElementById('morada').value;
    var nif=document.getElementById('nif').value;
    if(verp=='1' && veru=='1'){
        localStorage.setItem(user,pass + '|'+mor);
        sessionStorage.setItem(user,'ativo');
        window.location.href='login.html';

    }else{
        alert('ERRO');
    }
}

function logout(){
    var key='';
    var val='';
    for(var i=0;i<sessionStorage.length;i++){
        key = sessionStorage.key(i);
        val = sessionStorage.getItem(key);
        if(val=='ativo'){
            sessionStorage.setItem(key,'');
            window.location.href='login.html';
        }
    }
}
function isative(){
    var key='';
    var val='';
    var user='';
    for(var i=0;i<sessionStorage.length;i++){
        key = sessionStorage.key(i);
        val = sessionStorage.getItem(key);
        if(val=='ativo'){
            user = key;
        }else{
            user=0;
        }
    }
    return user;
}

function outstate(ative){
    var content='';
    if(ative!=0){
        alert(ative);
        content+= '<h6>O utilizador ' + ative+' esta online<h6>';
        content +='<button type="submit" onclick="logout();">LOGOUT</button>'
    }else{
        content +='<h6>NAO ESTA CONNECTADO<h6>';
    }
    return content
}
  • You didn’t mention where the problem is, is in the validation of some field, in the generation of some part of the page, errors occur? What initial code you developed?

  • Hello, Paulo. I suggest you edit your question and provide more information about your problem or questions. What have you tried to do? How do you want to do it? At what point are you encountering difficulties? Also add codes, if available..

  • @Fábio I put the code I have in the question :)

  • @Aline I put the code in the question :)

  • @Paulosolipa, what is going on with this code and what would you like to happen? I saw some problems in it, like the assignments of click and getelementbyid events in ids that don’t exist. But what do you expect?

  • This was a code that a friend of mine made to see if it worked. I had another code yet but it’s too long. The goal is to log in, detect if the user is registered and if this is not the case you will need to register and log in. Storing the data in Sesssion and Aline location. I will also post the other code but it has the same problem.

  • @Aline I could not format the code better. That’s why I put it like this. :/

Show 2 more comments

2 answers

0

[ EDITED ] At the time I posted this example there was no code in the question, I will analyze to find flaws and help.

Since you didn’t specify an error or something like that, I made a simple example of form with registration and login where you just need to send the data now to some controller or something like that and do both login and registration, you need to better define your question.

jQuery(document).ready(function(){
  jQuery('#formRegistro').submit(function(){
    alert('cadastrou campos : ' + jQuery(this).serialize());
    return false;
  });
  
  
  jQuery('#formLogin').submit(function(){
    alert('logou campos : ' + jQuery(this).serialize());
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" name="formRegistro" id="formRegistro">
  <input type="text" name="nome" id="nome" value="" required>
  <input type="password" name="senha" id="senha" value="" required>
  <input type="text" name="email" id="email" value="" required>
  <input type="submit" value="cadastrar">
</form>
<br>
<form method="POST" name="formLogin" id="formLogin">
  <input type="text" name="nome" id="nome" value="" required>
  <input type="password" name="senha" id="senha" value="" required>
  <input type="submit" value="logar">
</form>

0


I changed a few things in your HTML. I removed the onblur, which I didn’t understand because you were using it, so if you really need to, you should add it back. And also the email ID was wrong, according to what Voce was trying to get for js:

    <div>
        <form>
            <input type="email" id="user" required>
            <input type="password" id="pass" required>
            <button type="submit" disabled id="login" onclick="login();">LOGIN</button>
        </form>
    </div>

    <div>
        <input type="email" id="email" placeholder="Email" required>
        <span id="veruser"></span>
        <button style="text-decoration: none!important;display: none;" id="uservalue" value="0"></button>
        <input type="password" id="password" placeholder="Senha" required>
        <input type="password" id="confirmpassword" placeholder="Confirmação de senha" required>
        <span id="verpass"></span>
        <button style="text-decoration: none!important;display: none;" id="passvalue" value="0"></button>
        <input type="text" id="morada" placeholder="Rua" required>
        <input type="text" maxlength="9" id="nif" placeholder="Número" required>
        <button type="submit" id="registar" onclick="registar();">REGISTAR</button>
    </div>

As for JS, I’ve removed some functions I don’t know why you use, so in the same context, if you need to, add back

    <script>
        var armazenamento = []; //Obter no load da página os usuários que já estão no storage?

        function User(mail, password, morada, nif) {
            this.mail = mail;
            this.password = password;
            this.morada = morada;
            this.nif = nif;
        }

        function registar() {
            var usermail = document.getElementById('email').value;
            var emailJaExiste = armazenamento.filter(function (obj) {
                return obj.mail == usermail
            }).length;

            if (emailJaExiste) {
                alert("Email já cadastrado.")
                return;
            }

            var userpassword = document.getElementById('password').value;
            var usermorada = document.getElementById('morada').value;
            var usernif = document.getElementById('nif').value;
            localStorage.setItem(usermail, userpassword + '|' + usermorada);
            sessionStorage.setItem(usermail, 'ativo');
            armazenamento.push(new User(usermail, userpassword, usermorada, usernif));
        };

        function login() {
            //Verificar usuário existente. Array ou storage?
        }
    </script>

In this case, I did not search the data that was already in the Storage Database for initialization of the storage array, so it will only work for those registered on this page (without Load). Okay? You can improve this, I left commented.

Also just looked at the registration function, the login I left commented for you to look for where to find the Infos - array or Storage.

  • Thank you @Aline . I have just one question. If you want to store the data in a way that when doing Reload does not lose it, how do I do the code? I’m sorry to be a pain but my teacher didn’t teach me any of this

  • If you want to store in the same browser, in localStorage everything will be available unless you delete or clear the cache. But if you want to save effectively for future query and from anywhere, I suggest you research regarding database use.

  • OK Thank you so much @Aline !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.