Kiểm tra kiểu email và đường dẫn url trong PHP, là việc thường xuyên làm của các lập trình viên trong PHP.
Sau khi tạo dựng một Form thì tiếp theo là chúng ta kiểm tra xem người sử dụng có nhập đúng kiểu email và đường dẫn web (url) hay không.
Đoạn mã sau đây sẽ kiểm tra xem trường tên chỉ chứa các chữ cái và khoảng trắng. Nếu giá trị của trường tên không hợp lệ, sau đó lưu trữ thông báo lỗi:
1 2 3 4 |
$name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } |
Kiểm tra email
Mã nguồn bên dưới là, nếu địa chỉ e-mail không được định dạng đúng thì sẽ thông báo lỗi:
1 2 3 4 |
$email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } |
Kiểm tra đường dẫn url
Mã nguồn bên dưới là, nếu đường dẫn web url không đúng định dạng thì sẽ thông báo lỗi
1 2 3 4 |
$website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } |
Kiểm tra kiểu email và đường dẫn url trong PHP
Đây là mã nguồn PHP kiểm tra cả 2 kiểu email và url trong 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 42 43 44 45 46 47 48 49 |
<?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"]); } } ?> |