2012-12-26 92 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" > 
相关问题