6/1/17

[Ứng dụng PHP] Forms – Validate E-mail và URL

1. Validate Form với input text

$txtname = test_input($_POST["txtname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$txtname)) {
$nameErr = "Chỉ nhập chữ cái";
}

2. Validate E-mail

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Định dạng email không hợp lệ";
}

3. Validate URL

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Không đúng định dạng URL";
}

4. Validate Text, E-mail, và URL

<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Yêu cầu nhập tên";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Chỉ nhập chữ cái.";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email không để trống";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Không đúng định dạng Email";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Không đúng định dạng URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Nhập giới tính";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

Trên đây là hướng dẫn Validate E-mail và URL của chúng tôi.

0 nhận xét: