Moduli PHP - Convalida e-mail e URL
Questo capitolo mostra come convalidare nomi, e-mail e URL.
PHP - Convalida nome
Il codice seguente mostra un modo semplice per verificare se il campo del nome contiene solo lettere, trattini, apostrofi e spazi bianchi. Se il valore del campo del nome non è valido, archiviare un messaggio di errore:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
La funzione preg_match() ricerca una stringa per il modello, restituendo true se il modello esiste e false in caso contrario.
PHP - Convalida e-mail
Il modo più semplice e sicuro per verificare se un indirizzo e-mail è ben formato è utilizzare la funzione filter_var() di PHP.
Nel codice seguente, se l'indirizzo e-mail non è ben formato, memorizza un messaggio di errore:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Convalida URL
Il codice seguente mostra un modo per verificare se la sintassi di un indirizzo URL è valida (questa espressione regolare consente anche dei trattini nell'URL). Se la sintassi dell'indirizzo URL non è valida, archiviare un messaggio di errore:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
PHP - Convalida nome, e-mail e URL
Ora, lo script si presenta così:
Esempio
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
Il passaggio successivo consiste nel mostrare come impedire che il modulo svuoti tutti i campi di input quando l'utente invia il modulo.