2012-04-12 75 views
1

好的,我在本網站上查到的所有涉及驗證的內容都不是我要找的內容。preg_match驗證

我想要做的是在firstname和secondname中的值的最小長度和最大長度,這是我目前擁有的代碼。

 if (isset($_POST['submit'])) { 
     $errors = array(); 

       if (isset($_POST['firstname'])) { 
      $fn = $_POST['firstname']; 
     } else { 
      $errors[] = "You have not entered a first name"; 
     } 

     if (isset($_POST['secondname'])) { 
      $sn = $_POST['secondname']; 
     } else { 
      $errors[] = "You have not entered a second name"; 
     } 

我只是想知道如何將preg_match應用於那些最小值是4個字母,最大值是15的人嗎?

我不知道這件事情做

if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) 

在做這個,我試圖做

if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) { 

但是,這也給了我一個錯誤:/

誰能給我這是一個解決方案嗎?

謝謝!

更新: -

Nvm,我找到了解決辦法。我只是做這個

if (isset($_POST['firstname'])) { 
     if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) { 
      $fn = $_POST['firstname']; 
     } else { 
      $errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";     
     } 
    } else { 
     $errors[] = "You have not entered a name"; 

} 對於名字和secondname兩者。 :)

+2

爲什麼不使用'strlen()' – Michelle 2012-04-12 21:46:18

+0

*「但是這也給了我一個錯誤:/」* - 什麼錯誤?請將錯誤消息的文本添加到您的問題中。 – hakre 2012-04-12 21:48:33

+0

@hakre我正在做我的代碼作爲服務器端(而不是客戶端),因爲代碼是服務器端,當出現錯誤時,頁面變得空白。所以我不能提供它的錯誤代碼,如果它沒有出現。 – FizzyBear 2012-04-12 21:50:25

回答

0

我找到了解決辦法。我只是這樣做

if (isset($_POST['firstname'])) { 
      if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) { 
       $fn = $_POST['firstname']; 
      } else { 
       $errors[] = "<center> <h3>You must enter between 4 and 15 characters!</h3> </center>";     
      } 
     } else { 
      $errors[] = "You have not entered a name"; 
    } 

對於名字和secondname。

2

爲什麼不使用strlen()來獲取字符串長度,然後根據您的限制進行測試?

$length = strlen($nick); 
if ($length > 3 AND $length < 16) { 
    //Do STuff 
} else { 
    //Do stuff for failed requirement 
} 
+0

我正在嘗試使用preg_match,而不是strlen()。:) – FizzyBear 2012-04-12 22:16:35

+0

preg_match控制字符串中的最小字符數不是最好的方法!嘗試strlen()這有什麼問題? <?php $ min = 5; $最大= 25; $ len = strlen($ str); if((($ min!='')&&($ len <$ min))||(($ max!='')&&($ len> $ max)))echo「warning」else // DO STUFF ! – B4NZ41 2012-04-12 22:57:20