在我的PHP腳本中,我有這個輸入字段。如何設置文本輸入字段(html/php)的要求?
<input type="text" name="try" size="10" id="try" maxlength="5" >
什麼是簡單的方法,使我需要5個字符,並顯示錯誤消息,如果他們不只是字母。
在我的PHP腳本中,我有這個輸入字段。如何設置文本輸入字段(html/php)的要求?
<input type="text" name="try" size="10" id="try" maxlength="5" >
什麼是簡單的方法,使我需要5個字符,並顯示錯誤消息,如果他們不只是字母。
有了HTML5,你可以使用pattern
屬性:
<input type="text" name="try" size="10" pattern="[A-Za-z]{5}" title="5 alphabetic characters exactly">
這將使正好5個字符,這隻能是大寫或小寫字母。
<input type="text" pattern=".{5,}" required />
試試這個
這不起作用,因爲它缺少name =屬性。 –
你可以在客戶端使用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;
鑑於這樣之前驗證您的形式和使用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>";
}
還沒有測試這個可能會有語法錯誤。
假設頁面提交給自己。
快速和骯髒。
<?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" >
謝謝你這個作品完美無缺:) – Axxess
+1假設你不需要跨瀏覽器支持。我相信這不會在ie或safari上工作 - > [HTML5輸入模式](http://www.w3schools.com/html5/att_input_pattern.asp) – nienn
是的,它不會在IE或Safari上運行。 –