En este artículo aprenderás cómo validar formularios utilizando PHP, un lenguaje de programación del lado del servidor. Las validaciones del lado del servidor son más seguras y funcionan correctamente con todo tipo de navegadores. Despues de crear tu formulario HTML tendrás que validar sus campos y para ello, PHP cuenta con multitud de funciones y características que te ayudarán en el desarrollo de dichas validaciones.
En este tutorial, primero crearemos un formulario de registro de usuario típico a más no poder, y después validaremos sus campos utilizando funciones de PHP. ¿Te gusta la idea? ¡Pues vamos a ello!
Formulario de registro
A este archivo lo llamaremos index.php. Como ves, hay algo de código PHP embebido para mostrar los mensajes de error.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Server Side Form validations Using PHP</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
<?php
if(isset($error))
{
?>
input:focus
{
border:solid red 1px;
}
<?php
}
?>
</style>
</head>
<body>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<?php
if(isset($error))
{
?>
<tr>
<td id="error"><?php echo $error; ?></td>
</tr>
<?php
}
?>
<tr>
<td><input type="text" name="uname" placeholder="User Name" value="<?php if(isset($uname)){echo $uname;} ?>" <?php if(isset($code) && $code == 1){ echo "autofocus"; } ?> /></td>
</tr>
<tr>
<td><input type="text" name="email" placeholder="Your Email" value="<?php if(isset($email)){echo $email;} ?>" <?php if(isset($code) && $code == 2){ echo "autofocus"; } ?> /></td>
</tr>
<tr>
<td><input type="text" name="mno" placeholder="Mobile No" value="<?php if(isset($mno)){echo $mno;} ?>" <?php if(isset($code) && $code == 3){ echo "autofocus"; } ?> /></td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" <?php if(isset($code) && $code == 4){ echo "autofocus"; } ?> /></td>
</tr>
<tr>
<td><button type="submit" name="btn-signup">Sign Me Up</button></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>
En el anterior formulario de registro tenemos los siguientes campos:
- Nombre
- Contraseña
- Número de teléfono
Vamos a validar los siguientes aspectos:
- Valores vacíos
- Tamaño del valor del campo
- Si es un valor numérico
- Si el correo electrónico introducido es válido
Código PHP
Para validar el anterior formulario de registro, contaremos con la ayuda de PHP, un lenguaje del lado del servidor que nos proporciona para la validación una mayor seguridad y rendimiento. Añade el siguiente código PHP en el archivo index.php de antes, justo antes del tag HTML.
<?php
if(isset($_POST['btn-signup']))
{
$uname = trim($_POST['uname']);
$email = trim($_POST['email']);
$upass = trim($_POST['pass']);
$mno = trim($_POST['mno']);
if(empty($uname))
{
$error = "enter your name !";
$code = 1;
}
else if(!ctype_alpha($uname))
{
$error = "letters only !";
$code = 1;
}
else if(empty($email))
{
$error = "enter your email !";
$code = 2;
}
else if(!preg_match("/^[_.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+.)+[a-zA-Z]{2,6}$/i", $email))
{
$error = "not valid email !";
$code = 2;
}
else if(empty($mno))
{
$error = "Enter Mobile NO !";
$code = 3;
}
else if(!is_numeric($mno))
{
$error = "Numbers only !";
$code = 3;
}
else if(strlen($mno)!=10)
{
$error = "10 characters only !";
$code = 3;
}
else if(empty($upass))
{
$error = "enter password !";
$code = 4;
}
else if(strlen($upass) < 8 )
{
$error = "Minimum 8 characters !";
$code = 4;
}
else
{
?>
<script>
alert('success');
document.location.href='index.php';
</script>
<?php
}
}
?>
CSS
Llamaremos a este archivo style.css
@charset "utf-8"; /* CSS Document */ * { margin:0; padding:0; } #login-form { margin-top:70px; } table { border:solid #dcdcdc 1px; padding:25px; box-shadow: 0px 0px 1px rgba(0,0,0,0.2); } table tr,td { padding:15px; } table tr td input { width:97%; height:45px; border:solid #e1e1e1 1px; border-radius:3px; padding-left:10px; font-family:Verdana, Geneva, sans-serif; font-size:16px; background:#f9f9f9; transition-duration:0.5s; box-shadow: inset 0px 0px 1px rgba(0,0,0,0.4); } table tr td button { width:100%; height:45px; border:0px; background:rgba(12,45,78,11); background:-moz-linear-gradient(top, #595959 , #515151); border-radius:3px; box-shadow: 1px 1px 1px rgba(1,0,0,0.2); color:#f9f9f9; font-family:Verdana, Geneva, sans-serif; font-size:18px; font-weight:bolder; text-transform:uppercase; } table tr td button:active { position:relative; top:1px; } table tr td a { text-decoration:none; color:#00a2d1; font-family:Verdana, Geneva, sans-serif; font-size:18px; } #error { color: brown; font-family:Verdana, Geneva, sans-serif; font-weight:bolder; text-transform:capitalize; }
Fuente: codingcage.com