8. Forms 2
One of the most laborious tasks is validating information that comes from a form. It is dangerous to put anything that arrives into our Database. The user is clumsy or malicious.
- Entering nonsensical e-mails.
- Letters instead of numbers (for example when asking for the age).
- Leaving fields empty when they must be mandatory.
- Providing bad formats (for example in a phone number).
- A text length that is too short or too long.
- Malicious code.
- And a long etcetera.
There is no single way to validate, each programmer has their own method. But what you must always do are some strict steps:
- Send data from our form.
- Collect the data.
- Validate each field.
- Show the user the errors with a message.
- If there are errors, stay on the page.
- If there are no errors, generate the action you are looking for and inform the user of the success.
Even if you validate in Javascript (frontend) we must validate with PHP (backend). The data can be altered from the browser. Never trust the user!
Natively, PHP provides us with a function called filter_var.
filter_var('correo@ejemplo.com', FILTER_VALIDATE_EMAIL);
// True
We can only validate the format, not that it is a real email. For that there are third-party services such as Mailgun.
You can check the different validations available in validation filter types.
Below you can analyze a complete and real example where each field has been validated and the user is informed in case any problem is found.
<html>
<body>
<?php
//======================================================================
// PROCESS FORM
//======================================================================
// We check whether the data reaches us via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//-----------------------------------------------------
// Functions To Validate
//-----------------------------------------------------
/**
* Method that validates whether a text is not empty
* @param {string} - Text to validate
* @return {boolean}
*/
function validar_requerido(string $texto): bool
{
return !(trim($texto) == '');
}
/**
* Method that validates whether it is an integer number
* @param {string} - Number to validate
* @return {bool}
*/
function validar_entero(string $numero): bool
{
return filter_var($numero, FILTER_VALIDATE_INT);
}
/**
* Method that validates whether the text has a valid E-Mail format
* @param {string} - Email
* @return {bool}
*/
function validar_email(string $texto): bool
{
return filter_var($texto, FILTER_VALIDATE_EMAIL);
}
//-----------------------------------------------------
// Variables
//-----------------------------------------------------
$errores = [];
$nombre = isset($_REQUEST['nombre']) ? $_REQUEST['nombre'] : null;
$edad = isset($_REQUEST['edad']) ? $_REQUEST['edad'] : null;
$email = isset($_REQUEST['email']) ? $_REQUEST['email'] : null;
//-----------------------------------------------------
// Validations
//-----------------------------------------------------
// Name
if (!validar_requerido($nombre)) {
$errores[] = 'The Name field is mandatory.';
}
// Age
if (!validar_entero($edad)) {
$errores[] = 'The Age field must be a number.';
}
// Email
if (!validar_email($email)) {
$errores[] = 'The Email field has an invalid format.';
}
//-----------------------------------------------------
// Logic
//-----------------------------------------------------
if (!isset($errores)) {
// We send the email
}
}
?>
<!-- We show errors via HTML -->
<?php if (isset($errores)): ?>
<ul class="errores">
<?php foreach ($errores as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- Form -->
<form method="post">
<p>
<!-- Name field -->
<input type="text" name="nombre" placeholder="Name">
</p>
<p>
<!-- Age field -->
<input type="text" name="edad" placeholder="Age">
</p>
<p>
<!-- Email field -->
<input type="text" name="email" placeholder="Email">
</p>
<p>
<!-- Submit button -->
<input type="submit" value="Send">
</p>
</form>
</body>
</html>
You can use it as a base for future work.
Activity 1
Build a form to buy headphones.
- The fields will be: email and units.
- Each unit costs 29.95 euros.
- Send an email, to the address they have entered, with the following text.
Thank you for buying our "Carmencita" headphones!
Invoice:
(number) units at 29.95 euros each.
Total: (total) euros
Activity 2
You are in charge of notifying all the fans of Madonna's new European tour. You must send an HTML email with the list of cities.
| Date | City |
|---|---|
| 27/5 | London |
| 13/6 | Berlin |
| 5/7 | Paris |
| 8/8 | Valencia |
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.