PHP - Validar contraseñas iguales

 
Vista:
sin imagen de perfil

Validar contraseñas iguales

Publicado por Sebastian (35 intervenciones) el 20/05/2015 06:40:43
Saludos, necesito de su apoyo y conocimiento

Mi problema es el siguiente. En un formulario tengo dos campos uno de contraseña y otro confirmar contraseña, necesito que me compare esos campos y si son diferentes me muestre un mensaje de alerta, si son iguales simplemente no hace nada.

Este es todo el código que tengo para hacer el registro, el problema es que no se en que parte de mi código insertar la validación..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
 
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO usuario (usu_usuario, usu_password, usu_nombres, usu_apellidos, usu_telefono, usu_nac, usu_direccion, usu_email, tipousu_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['usu_usuario'], "text"),
                       GetSQLValueString($_POST['usu_password'], "text"),
                       GetSQLValueString($_POST['usu_nombres'], "text"),
                       GetSQLValueString($_POST['usu_apellidos'], "text"),
                       GetSQLValueString($_POST['usu_telefono'], "text"),
                       GetSQLValueString($_POST['usu_nac'], "date"),
                       GetSQLValueString($_POST['usu_direccion'], "text"),
                       GetSQLValueString($_POST['usu_email'], "text"),
                       GetSQLValueString($_POST['usu_tipo'], "int"));
 
	mysql_select_db($database_prueba, $prueba);
	$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());
 
 
	$insertGoTo = "registrarusuarios.php";
 
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
	echo ' <script language="javascript"> alert("Usuario registrado con éxito");</script> ';
  }
  header(sprintf("Location: %s", $insertGoTo));
 
}
?>

De aqui tomo las contrasenias ingresadas

1
2
3
4
5
6
7
8
9
10
11
12
<div class="form-group">
            <label class="control-label col-xs-3" for="inputPassword">Contraseña:</label>
            <div class="col-xs-9">
                <input type="password" class="form-control" id="usu_password" name="usu_password" value="" placeholder="Contraseña" required="required">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-xs-3" for="confirmPassword">Confirmar Contraseña:</label>
            <div class="col-xs-9">
                <input type="password" class="form-control" id="usu_confirm" name="usu_confirm" placeholder="Confirmar Contraseña" required="required">
            </div>
        </div>

PD. Para hacer el registro utilice dreamweaver
Ojala me puedan ayudar muchas gracias...
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.943
Oro
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Validar contraseñas iguales

Publicado por xve (6935 intervenciones) el 20/05/2015 08:34:53
Hola Sebastian, esto se puede hacer de dos maneras, una validarlo en JavaScript y luego en PHP, o únicamente en PHP

Si lo quieres hacer en PHP, es simple...

1
2
3
4
5
6
if($_POST["usu_password"]==$_POST["usu_confirm"])
{
     # son iguales
}else{
     # no son iguales
}

Con javascrip es un poquito mas complicado ya que tienes que hacerlo antes del submit del formulario... si te interesa me lo comentas y te preparo un ejemplo, ok?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil

Validar contraseñas iguales

Publicado por Sebastian (35 intervenciones) el 20/05/2015 08:45:43
Gracias por responder xve.

He hecho lo siguiente

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
if (!function_exists("GetSQLValueString")) {
			function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
			{
			  if (PHP_VERSION < 6) {
				$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
			  }
 
			  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
			  switch ($theType) {
				case "text":
				  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
				  break;
				case "long":
				case "int":
				  $theValue = ($theValue != "") ? intval($theValue) : "NULL";
				  break;
				case "double":
				  $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
				  break;
				case "date":
				  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
				  break;
				case "defined":
				  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
				  break;
			  }
			  return $theValue;
			}
			}
			$editFormAction = $_SERVER['PHP_SELF'];
			if (isset($_SERVER['QUERY_STRING'])) {
			  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
			}
 
		if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
			  $insertSQL = sprintf("INSERT INTO usuario (usu_usuario, usu_password, usu_nombres, usu_apellidos, usu_telefono, usu_nac, usu_direccion, usu_email, tipousu_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
								   GetSQLValueString($_POST['usu_usuario'], "text"),
								   GetSQLValueString($_POST['usu_password'], "text"),
								   GetSQLValueString($_POST['usu_nombres'], "text"),
								   GetSQLValueString($_POST['usu_apellidos'], "text"),
								   GetSQLValueString($_POST['usu_telefono'], "text"),
								   GetSQLValueString($_POST['usu_nac'], "date"),
								   GetSQLValueString($_POST['usu_direccion'], "text"),
								   GetSQLValueString($_POST['usu_email'], "text"),
								   GetSQLValueString($_POST['usu_tipo'], "int"));
 
				if ($_POST['usu_password'] != $_POST['usu_confirm'])
					{
						?>
							<script>
 
							alert('Las claves no coinciden');
							location.href = "registrarusuarios.php";
							</script>
 
						<?php 
 
					}
				else
			{
						mysql_select_db($database_prueba, $prueba);
						$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());
						$insertGoTo = "registrarusuarios.php";
 
 
					  if (isset($_SERVER['QUERY_STRING'])) {
						$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
						$insertGoTo .= $_SERVER['QUERY_STRING'];
						echo ' <script language="javascript"> alert("Usuario registrado con éxito");</script> ';
					  }
					  header(sprintf("Location: %s", $insertGoTo));
			}
		}
		}

Mediante javascript pongo mi mensaje de alerta, pero no estoy seguro si es la parte correcta donde estoy validando.

Al dar clic en el boton submit del formulario me hace la validacion y me muestra el mensaje pero el mensaje se carga en una pagina en blanco, luego de aceptarlo me borra todos los campos que ya he ingresado en mi formulario.

Lo ideal seria que el mensaje aparezca en la misma pagina del formulario y que solo me borre el texto que he ingresado en las contrasenias.

No se que estoy haciendo mal talvez en location.href = "registrarusuarios.php"; o debo poner la validación en otra parte???

Gracias por ayudarme...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Validar contraseñas iguales

Publicado por Daniel (1 intervención) el 31/07/2016 22:09:00
hola sebastian no entiendo porque en la linea 50 cierras php y en la 57 lo abres si se supone ya estas escribiendo en un documento php
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar