Validate Fields and Form Submit

Asked

Viewed 200 times

2

In this script below I validate the fields if the password is equal i’m not sure how to make the form only work if the password is equal

<script>
function validarSenha() {
  NovaSenha = document.FormSenha.Password.value
  CNovaSenha = document.FormSenha.CNovaSenha.value

  if (NovaSenha == CNovaSenha) {
    $("#status2").slideDown();
    $("#status2").html(" Senha OK"); // abre minha div
    // regra para fazero o formulario enviar
    setTimeout(function() { // fecha minha div
      $("#status2").remove();
    }, 5000);
  } else {
    $("#status").slideDown();
    $("#status").html(" A Segunda senha não confere");
    // regra para não fazer o formulario enviar                     
    setTimeout(function() { // 
      $("#status").remove();
    }, 5000);
  }
} 
</script>

<?
date_default_timezone_set('America/Sao_Paulo');
$datalog = date('Y-m-d');
$horalog = date('H:i:s');
$ip = file_get_contents('https://api.ipify.org'); // Pega o ip WAN
   echo $id = $_SESSION["id_user"];

    $acao = $_REQUEST["ac"];
    $id_user = $_REQUEST["err"];
    $acao2 = $_REQUEST["ac2"];
    
if ($acao == 'troc'){
require_once("sis/gerenciador/assets/lconfig.php");     
       
       
                     
          if (isset($_REQUEST['submit'])) { 
        $id_user = $_REQUEST["err"];
        $senha_a = md5(trim($_REQUEST["senha_antiga"])); 



$sql = mysql_query("SELECT * FROM usuarios WHERE id_user='$id_user' AND senha_n = '$senha_a' "); 
    $dados = mysql_fetch_array($sql); 


if(mysql_num_rows($sql) <= 0){

$alert = '<div style=" 
                        color: white; 
                        height: 50px; 
                        border-style: solid;
                        background-color: red;padding-left: 20px; padding-top: 8px; border-radius: 10px; font-size: 14px;"> 
Senha Antiga não confere
</div>
';

$sql = mysql_query ("INSERT INTO log 
(id_transfer,id_user,acao,usuario,data,ip)VALUES
('$id_transfer1','$id_user','Senha Tentativa de Trocar Senha','$login','$datalog.$horalog','$ip')", $conecta) or die( mysql_error());

    
}else{

$alert = '<div style=" 
                        color: white; 
                        height: 50px; 
                        border-style: solid;
                        background-color: green;padding-left: 20px; padding-top: 8px; border-radius: 10px; font-size: 14px;"> 
Senha Alterada com Sucesso
</div>
';


     $Password = md5(trim($_REQUEST["Password"])); 

$consulta = "UPDATE usuarios SET senha_n = '$Password',acesso = '0' 
WHERE id_user = '$id_user'";
$resultado = mysql_query($consulta) or die( mysql_error());

    
$sql = mysql_query ("INSERT INTO log 
(id_transfer,id_user,acao,usuario,data,ip)VALUES
('$id_transfer1','$id_user','$id_user Alterou sua Senha','$login','$datalog.$horalog','$ip')", $conecta) or die( mysql_error());
    

}}




?>

<!DOCTYPE html>
<html class="fluid top-full sticky-top sidebar sidebar-full">

 

<head>
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
    <title>Go Transfer - Sistema de Gest&atilde;o para empresas de Transporte Executivo e Receptivo</title>	<meta name="Transfer-Online" content="width=device-width, initial-scale=1.0">	<meta name="author" content="transfer-online.net">			<link rel="shortcut icon" href="assets/images/favicon.png" type="image/png">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
	<link rel="stylesheet" href="sis/gerenciador/assets/css/admin/module.admin.page.login.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" integrity="sha384-aUGj/X2zp5rLCbBxumKTCw2Z50WgIr1vs/PFN4praOTvYXWlVyh2UtNUU0KAUhAX" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>

<script src="https://github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min.js"></script>

<!----------------------------comparando senha---------------------------------------->
<script>
function validarSenha() {
  NovaSenha = document.getElementById("Password").value;
  CNovaSenha = document.getElementById("CNovaSenha").value;

  if (NovaSenha != CNovaSenha) {
    $("#status2").slideDown();
    $("#status2").html("A Segunda senha não confere");
    setTimeout(function() { $("#status2").remove(); }, 5000);
    return false;
  }

  return true;
} 
</script>

<!----------------------------------meter-------------------------------------------------------------->
    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        window.alert = function(){};
        var defaultCSS = document.getElementById('bootstrap-css');
        function changeCSS(css){
            if(css) $('head > link').filter(':first').replaceWith('<link rel="stylesheet" href="'+ css +'" type="text/css" />'); 
            else $('head > link').filter(':first').replaceWith(defaultCSS); 
        }
        $( document ).ready(function() {
          var iframe_height = parseInt($('html').height()); 
          window.parent.postMessage( iframe_height, 'http://bootsnipp.com');
        });
    </script>
<script language="javascript" src="sis/gerenciador/assets/js/meter/meter.js"></script>
<!----------------------------------meter-------------------------------------------------------------->

</head>
<body class="login ">
<?echo $alert?>
<div id="status" style="display: none;  
                        color: white; 
                        height: 50px; 
                        border-style: solid;
                        background-color: red;padding-left: 20px; padding-top: 8px; border-radius: 10px; font-size: 14px;"> 

</div>

<div id="status2" style="display: none;  
                        color: white; 
                        height: 50px; 
                        border-style: solid;
                        background-color: green;padding-left: 20px; padding-top: 8px; border-radius: 10px; font-size: 14px;"> 

</div>


<br /><br />
<h2 style="text-align: center;"> Alterar Senha</h2>
<div id="login">
    <div class="col-md-4"></div>
    <div class="col-md-4">
	<div class="wrapper"><br />
	<div class="widget widget-heading-simple widget-body-gray">
	<div class="widget-body">
	<form method="POST" onsubmit="validarSenha() class="form" id="FormSenha" name="FormSenha" action="troca.php" >
				        
                        <input type="hidden" name="ac"  value="troc"/>
                        <input type="hidden" name="err"  value="<?echo $id_user?>"/>
						<input type="hidden" class="form-control" name="login"    value="<?echo $login?>"/> 
                        <input type="hidden" class="form-control" name="login"  value=""/> 
						<label>Senha Antiga:</label>
						<input type="password" class="form-control"  maxlength="12" size="12"  name="senha_antiga" placeholder="Senha" />
                        <label>Nova Senha:</label>
						<input class="form-control" required=""  id="Password" name="Password" data-val="true" data-val-length="Minimo 6 caracteres." data-val-length-max="100" data-val-length-min="6" data-val-required="password is required" placeholder="min 6 caracteres" maxlength="12" rows="12" type="password" />
                        <div id="pw-val-container">
                          <div id="pw-val-progress">
                                        <div id="pw-val-verdict"></div>
                                        <div id="pw-val-errors"></div>
                          </div>
                        
                        <label>Repita a Senha:</label>
                        <input type="password" required="" class="form-control"  maxlength="12" size="12" id="CNovaSenha" onblur="validarSenha()"  name="senha2" placeholder="Repita" />
				
						<a class="password" href="">Esqueceu sua senha?</a>
	                    <div class="separator bottom clearfix"></div>
						<div class="row">
						<div class="col-md-8">
						<button  class="btn btn-block btn-inverse" onblur="validarSenha()" name="submit" type="submit">Alterar</button></div>
						<div class="col-md-4 center"><button  class="btn btn-block" style="background-color: #8080FF; color: white;" onblur="validarSenha()" name="submit" type="submit">Logar</button></div>
	</div>
	</form></div></div></div></div>
        <div class="col-md-4">      
                    
    </div>

    <div class="col-md-2"></div></div>
    </div></div>
	<div class="container">
    <div class="row">
    <div class="col-md-12"<br /><h3 style="text-align: center;"><strong> Sistema de Gest&atilde;o Integrada    </strong></h3>
    <h6 style="text-align: center;">Todos os direitos reservados a Mpitech</h6>
    <div class="widget-body" style="text-align: right;">
	</p>
    </div></div></div></div>
 
<?}?>

2 answers

0

One thing you can do, if you’re not already doing it, is call the function validarSenha at the event onsubmit form:

<form ... onsubmit="validarSenha()">

This way, when the user presses the send button, the function will be called, validating the passwords. Interestingly, if this function returns true, the request is propagated naturally, as you defined in action form. But if you return false, the request is canceled. In this case, it is best you just check when passwords are not equal, as below:

function validarSenha() {
  var NovaSenha = document.getElementById("Password").value;
  var CNovaSenha = document.getElementById("CNovaSenha").value;

  if (NovaSenha != CNovaSenha) {
    $("#status2").slideDown();
    $("#status2").html("A Segunda senha não confere");
    setTimeout(function() { $("#status2").remove(); }, 5000);
    return false;
  }

  return true;
} 

That is, if the password is different, the error message appears and returns false, canceling the request of the form. Otherwise, returns true, allowing the form to be sent.

  • tried here still this running the same <form with different password es

  • Is there any way to post the code? I believe I can edit the question by adding the new code at the end.

  • I put the full code

  • Console shows some error?

  • here no....

  • Resolved by putting $("#Formpassword"). Submit(Function(){ Return false; });

  • but he only checks once , I need to give a Load to redo the checkVoce would know why of this?

Show 2 more comments

0

I came up with a solution that worked

$("#FormSenha").submit(function(){
return false; 
});  

function validarSenha() {
  NovaSenha = document.FormSenha.Password.value
  CNovaSenha = document.FormSenha.CNovaSenha.value

  if (NovaSenha == CNovaSenha) {
    $("#status2").slideDown();
    $("#status2").html(" Senha OK"); // abre minha div
    $("#FormSenha").submit(function(){
    return true; 
    });  
    setTimeout(function() { // fecha minha div
      $("#status2").remove();
    }, 5000);
    return true
  } else {
    $("#status").slideDown();
    $("#status").html(" A Segunda senha não confere");
    // regra para não fazer o formulario enviar                     
    $("#FormSenha").submit(function(){
    return false; 
    });
    setTimeout(function() { // 
      $("#status").remove();
    }, 5000);
    return false
  }
} 

Browser other questions tagged

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