4

In my php script i have this input field.

   <input type="text" name="try" size="10" id="try" maxlength="5" >

What is the easy way to make i require 5 characters and show an error message if they are not only letters.

4

5 回答 5

3

使用 HTML5,您可以使用以下pattern属性:

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

这将允许正好 5 个字符,只能是大写或小写字母字符。

于 2012-12-26T17:23:29.880 回答
2

您可能可以在客户端的 jQuery 中做到这一点。您还需要在服务器端执行此操作,因为 JavaScript 可以(并且将)被攻击媒介绕过。像这样的正则表达式将在 PHP 中进行服务器端验证。

$rgx = '/[AZ]{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;
于 2012-12-26T17:23:47.593 回答
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" >
于 2012-12-26T17:29:44.077 回答
1
<input type="text" pattern=".{5,}" required />

尝试这个

于 2012-12-26T17:23:03.863 回答
1

validate your form before view like this and use strlen to check the length of input:

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>";
}

Haven't tested this so might have syntax errors.

于 2012-12-26T17:25:02.880 回答