Validacion de formularios con PHP y JS
Miércoles, 5. Agosto 2009
Bueno aqui unos simples ejemplos ^^
PHP:
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 | <!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" xml:lang="en" lang="en"> <head> <style type="text/css"> #contenedor{ text-align: center; } #validar{ border: 1px #C0C0C0 solid; } #boton{ border: 1px #C0C0C0 solid; } </style> </head> <body> <br /> <div id="contenedor"> <form action="" name="asd" method="POST"> <label>Campo a validar</label> <br /> <input type="text" id="validar" name="validar" size="30" maxlength="30" /> <br /> <br /> <?php //Comprobamos que este vacio if (isset($_POST['validar'])) { $validar = htmlspecialchars(trim($_POST['validar'])); //comprobamos que no este vacio al mandar el formulario if ($validar == '') { echo "<label>El campo " . $validar . " esta vacio</label> <br />"; } } ?> <input type="submit" id="boton" value="Validar"> </form> </div> </body> </html> |
JS:
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 | <!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" xml:lang="en" lang="en"> <head> <script type="text/javascript"> //iniciamos la funcion para la validacion function validacion() { //obtenemos el valor del campo por DOM var validar = document.getElementById('validar'); var nvalidar = validar.name; //comprobamos que no este vacion el campo if (validar.value == '') { alert("El campo " + nvalidar + " esta vacion"); } else { //si no esta vacio el campo, mandamos formulario document.forms.asd.submit(); } } </script> <style type="text/css"> #contenedor{ text-align: center; } #validar{ border: 1px #C0C0C0 solid; } #boton{ border: 1px #C0C0C0 solid; } </style> </head> <body> <br /> <div id="contenedor"> <form action="" name="asd" method="POST"> <label> Campo a validar </label> <br /> <input type="text" id="validar" name="validar" size="30" maxlength="30" /> <br /> <br /> <input type="button" id="boton" value="Validar" onclick="validacion()"> </form> </div> </body> </html> |