0
Good night. I am two days trying to validate a form that will save the data of the user registration in the browser localstorage. I received part of the code ready, the problem is that the form saves the empty data, so anyone can enter just by clicking on the registration button and then on the login button. I tried using an "if" to detect when the elements are empty and display an alert, but it displays and prevents data from being saved even when the fields are full. I’m desperate about it. Can someone help me? I am extremely grateful to all!
var operacao = "A"; //"A"=Adição; "E"=Edição
var indice_selecionado = -1; //Índice do item selecionado na lista
var tbUsuarios;
$(function () {
tbUsuarios = localStorage.getItem("tbUsuarios");// Recupera os dados armazenados
tbUsuarios = JSON.parse(tbUsuarios); // Converte string para objeto
if (tbUsuarios == null) // Caso não haja conteúdo, iniciamos um vetor vazio
tbUsuarios = [];
});
function Adicionar() {
var usuario = JSON.stringify({
Nome: $("#txtNome").val(),
email: $("#txtEmail").val(),
Senha: $("#txtSenha").val()
});
if ($('#txtNome').is(':empty') || $('#txtEmail').is(':empty') || $('#txtSenha').is(':empty')){
alert('Preencha os campos vazios');
}
else{
tbUsuarios.push(usuario);
localStorage.setItem("tbUsuarios", JSON.stringify(tbUsuarios));
alert("Usuário Cadastrado com Sucesso!");
return true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="formRegister" id="formRegister" class="positionFormRegister">
<!--nome de usuario-->
<div class="input-group">
<span class="input-group-addon"></span>
<label></label>
<input name="txtName" id="txtNome" type="text" class="form-control" placeholder="Crie seu nome de Usuário" autocomplete="off">
</div>
<!--email-->
<div class="input-group">
<span class="input-group-addon"></span>
<label></label>
<input name="txtEmail" id="txtEmail" type="text" class="form-control" placeholder="Seu endereço de e-mail" autocomplete="off">
</div>
<!--senha-->
<div class="input-group">
<span class="input-group-addon"></span>
<label></label>
<input name="txtSenha" id="txtSenha" type="password" class="form-control" placeholder="Crie sua senha" autocomplete="off">
</div>
<!--botão submit-->
<div>
<input id="buttonSubmitRegister" type="submit" class="btn btn-primary btn-lg positionFormRegister" value="Cadastrar no e-Pro »" onclick="Adicionar()">
</div>
</form>
Perfect!!!! Thank you very much, it worked well. Now I will make custom alerts with modals for each field. Thank you!!!
– Mauricio Hartmann