PHP Form Validation - Validate E-mail and URL
- পূর্ববর্তী পৃষ্ঠা PHP ফর্ম বাধ্যতামূলক
- পরবর্তী পৃষ্ঠা PHP ফর্ম কমপ্লিট
This section shows how to validate names, emails, and URLs.
PHP - Validate Name
The following code demonstrates a simple method to check if the name field contains letters and spaces. If the name field is invalid, then store an error message:
$name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and spaces allowed!"; }
Note:The preg_match() function retrieves the pattern of the string, and returns true if the pattern exists, otherwise returns false.
PHP - Validate E-mail
The following code demonstrates a simple method to check if the e-mail address syntax is valid. If it is invalid, then store an error message:
$email = test_input($_POST["email"]); if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format!"; }
PHP - Validate URL
The following code demonstrates a method to check if the URL syntax is valid (this regular expression also allows slashes in the URL). If the URL syntax is invalid, then store an error message:
$website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%", =~_|]/i,$website)) { $websiteErr = "Invalid URL"; }
PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
Example
<?php // Define variables and set them 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"; } $name = test_input($_POST["name"]); // নাম কীর্তির বর্তমান বাক্যবলিতে পরীক্ষা করুন if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } $email = test_input($_POST["email"]); // ইমেইল ঠিকানার বর্তমান বাক্যবলিতে পরীক্ষা করুন if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; } $website = test_input($_POST["website"]); // Check if the URL address language is valid (this regular expression also allows underscores in URLs) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%", =~_|]/i,$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } $gender = test_input($_POST["gender"]); } } ?>
এখন আমি আপনাকে শিখাব যে, ফর্মটি ব্যবহারকারীর দ্বারা ফর্ম সম্পাদন করা হলে সমস্ত ইনপুট ফিল্ডগুলি কিভাবে খালি করা যায়。
- পূর্ববর্তী পৃষ্ঠা PHP ফর্ম বাধ্যতামূলক
- পরবর্তী পৃষ্ঠা PHP ফর্ম কমপ্লিট