PHP-如何在文本字段中只允许字母。还有如何只允许文本字段中的数字

新手上路,请多包涵

如何添加只接受字母的输入字段。另外我如何添加一个只接受数字的输入字段。一旦用户在只接受数字的文本字段中输入说字母,它就会出错。

 if(empty($_POST['firstname']))
        {
            $errors['firstname1'] = " Required";
        }

    if(empty($_POST['zip']))
        {
            $errors['zip1'] = " Required";
        }

    <!-- Letters only for firstname -->

    <p>
                <label for="firstname" class="label"><font color="#040404">*First Name:</font></label>
                <input class="textinput" id="firstname" type="text" name="firstname" value="<?php if(isset($_POST['firstname'])) echo $_POST['firstname']; ?>" /><?php if(isset($errors['firstname1'])) echo $errors['firstname1']; ?>
            </p>
    <!-- Letters only for zip -->

    <p>

                    <label for="zip" class="label"><font color="#040404">*Zip Code:</font></label>
                    <input id="zip" type="text" name="zip" value="<?php if(isset($_POST['zip'])) echo $_POST['zip']; ?>" /><?php if(isset($errors['zip1'])) echo $errors['zip1']; ?> <?php if(isset($errors['zip2'])) echo $errors['zip2']; ?>
                </p>

原文由 Shiv Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 285
1 个回答

考虑在表单验证中使用 PHP 函数 ctype_alphactype_digit

ctype_alpha 仅当验证由字母组成时才返回 true,如果使用数字或特殊字符,则返回 false。

ctype_digit 仅当验证由数字组成时才返回 true,如果使用字母或特殊字符则返回 false。

这是一个检查数组的简单示例。它将返回 false,因为其中一个字符串中有一个数字:

 $string = array('word', 'number5');
if (ctype_digit($string)) {
    echo "All numbers are true!";
} else {
    echo "Something's not right";
}

希望这可以帮助!

原文由 sktwentysix 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题