2012-12-26 87 views

回答

3

有了HTML5,你可以使用pattern屬性:

<input type="text" name="try" size="10" pattern="[A-Za-z]{5}" title="5 alphabetic characters exactly"> 

這將使正好5個字符,這隻能是大寫或小寫字母。

+0

謝謝你這個作品完美無缺:) – Axxess

+2

+1假設你不需要跨瀏覽器支持。我相信這不會在ie或safari上工作 - > [HTML5輸入模式](http://www.w3schools.com/html5/att_input_pattern.asp) – nienn

+0

是的,它不會在IE或Safari上運行。 –

1
<input type="text" pattern=".{5,}" required /> 

試試這個

+0

這不起作用,因爲它缺少name =屬性。 –

2

你可以在客戶端使用jQuery來做到這一點。您還需要在服務器端執行此操作,因爲JavaScript可以(也將會)被攻擊媒介繞過。像這樣的正則表達式將在PHP中進行服務器端驗證。

$ rgx ='/ [A-Z] {5,}/i';

相結合的辦法......

http://www.laprbass.com/RAY_temp_axxess.php?q=abcde
http://www.laprbass.com/RAY_temp_axxess.php?q=ab
http://www.laprbass.com/RAY_temp_axxess.php?q=abcdefg

<?php // RAY_temp_axxess.php 
error_reporting(E_ALL); 

// A REGEX FOR 5+ LETTERS 
$rgx = '/^[A-Z]{5,}$/i'; 

if (isset($_GET['q'])) 
{ 
    if (preg_match($rgx, $_GET['q'])) 
    { 
     echo 'GOOD INPUT OF 5+ LETTERS IN '; 
    } 
    else 
    { 
     echo "VALIDATION OF {$_GET['q']} FAILED FOR REGEX: $rgx"; 
    } 
} 

// CREATE THE FORM 
$form = <<<ENDFORM 
<form> 
<input type="text" name="q" pattern="[A-Za-z]{5,}" title="At least 5 alphabetic characters" /> 
<input type="submit" /> 
</form> 
ENDFORM; 
echo $form; 
+0

極好的php函數我必須使用這個工作嗎? – Axxess

+0

更新後最有趣 – Axxess

+0

我只在FF和Chrome上測試過。兩者都有預期的瀏覽器響應。當然,如果是直接輸入,只有服務器測試纔會執行,所以這就是爲什麼你需要腰帶和吊帶;-) –

1

鑑於這樣之前驗證您的形式和使用strlen來檢查輸入的長度:

if(isset($_POST['mySubmit'])) { 
    if(strlen($_POST['try']) < 5) { 
     $error = "Too short"; 
    } 
    else { 
     $valid = true; 
     //Do whathever you need when form is valid 
    } 
} 
else { 
    if(isset($error)) { 
     echo "<p>$error</p>"; 
    } 

    //echo your form here 
    echo "<form method='post' action='thisPhpScript.php'> 
       <input type='text' name='try' size='10' id='try' maxlength='5' > 
      </form>"; 
} 

還沒有測試這個可能會有語法錯誤。

+0

以及如何檢查是否有數字或特殊字符? – Axxess

+0

使用preg_match()! – HamZa

+0

現在就試試吧! :) – Axxess

1

假設頁面提交給自己。

快速和骯髒。

<?php 
$errors = array(); 
if (isset($_POST['try']) & strlen($_POST['try']) != 5 & ctype_alpha($_POST['try'] != true) { 
$error['try'] = "This field must contains 5 characters and contain only a-z and A-Z"; 
// stop whatever you normally do if submitted. 
} 
?> 

稍後顯示此字段的頁面上。

<?php if (isset($errors['try'])) { echo $errors['try']; } ?> 
<input type="text" name="try" size="10" id="try" maxlength="5" > 
相關問題