在我的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上运行。 –