【发布时间】:2012-12-12 04:50:59
【问题描述】:
在我的 php 脚本中,我有这个输入字段。
<input type="text" name="try" size="10" id="try" maxlength="5" >
有什么简单的方法可以让我需要 5 个字符并在它们不仅仅是字母时显示错误消息。
【问题讨论】:
在我的 php 脚本中,我有这个输入字段。
<input type="text" name="try" size="10" id="try" maxlength="5" >
有什么简单的方法可以让我需要 5 个字符并在它们不仅仅是字母时显示错误消息。
【问题讨论】:
您可能可以在客户端的 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" >
【讨论】:
对于 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 />
试试这个
【讨论】: