Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Forms - Validating Email and URL

PHP Forms - Validating Email and URL


This section will introduce how to validate names, e-mails, and URLs.


PHP - Validating Name

The code below uses a simple way to check whether the name field contains only letters and whitespace; if the name field value is invalid, an error message will be output:



$name = test_input($_POST["name"]);

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {

  $nameErr = "Only letters and spaces are allowed"; 

}

| Note | preg_match — performs a regular expression match.

 语法:       

 

int preg_match ( string $pattern , string $subject [, array $matches [, int $flags ]] )

在 subject 字符串中搜索与 pattern 给出的正则表达式相匹配的内容。如果提供了 matches ,则其会被搜索的结果所填充。$matches[0] 将包含与整个模式匹配的文本,$matches[1] 将包含与第一个捕获的括号中的子模式所匹配的文本,以此类推。 |

| --- | --- |


PHP - Validating Email

The code below uses a simple way to check whether the e-mail address is valid. If the e-mail address is invalid, an error message will be output:



$email = test_input($_POST["email"]);

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {

  $emailErr = "Invalid email format"; 

}


PHP - Validating URL

The code below checks whether the URL address is valid (the following regular expression allows the URL to contain dashes: "-"); if the URL address is invalid, an error message will be output:



$website = test_input($_POST["website"]);

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {

  $websiteErr = "Invalid URL address"; 

}


PHP - Validating Name, E-mail, and URL

The code is shown below:





Run Example »