PHP-如何在文本字段中只允许使用字母.以及如何在文本字段中只允许数字


PHP- how to allow only letters in a text field. Also how to only allow numbers in a text field

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

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>

考虑使用PHP函数ctype_alpha&ctype_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";
}

希望这能有所帮助!

如何在文本字段中只允许使用字母。

您可以使用HTML5的pattern属性来只允许文本字段中的字母,如下所示:

<input type="text" name="fieldname1" pattern="[a-zA-Z]{1,}" required>

如何只允许文本字段中的数字

类似地,使type属性number只允许文本字段中的数字,如下所示:

<input type="number" name="fieldname2" required>

或者,使用pattern属性,如下所示:

<input type="text" name="fieldname2" pattern="[0-9]{1,}" required>

旁注:尽管客户端上的这些输入字段会在一定程度上限制用户,但它们并不可靠,也是您唯一的防线。在服务器端上使用PHP Regex来严格验证输入数据。

你不需要写任何额外的代码来满足你的要求

下面是一个只允许字母(在任何序列中都是小写和大写)的示例。

<input id="my_id" type="text" pattern="[A-Za-z]*" class="validate">

或者你可以给出更多的限制,比如只允许第一个字母是大写的,并用pattern="[A-Z][a-z]*" 用小帽扩孔

要只允许数字使用pattern="[0-9]*",并且只允许固定数字(例如10),请使用pattern="[0-9]{10}"

使用此:

   function removeInvalidCharacters($input, $allowedChars = 'abcdefghijklmnopqrstuvwxyz 1234567890')
    {
        $str = '';
        for ($i   = 0; $i < strlen($input); $i++)
        {
            if (!stristr($allowedChars, $input[$i]))
            {
                continue;
            }
            $str .= $input[$i];
        }
        return $str;
    }

仅针对数字,以下是我在jQuery中使用的片段:

$('.content').keydown(function(e){
    var c = (e.charCode || e.keyCode);
    if(c<48 || c>57){
        return false;
    }else{
        return true;
    }
});

注意:这只适用于PHP

如果你想用PHP在服务器端进行验证,你可以使用:

function validate_string_spaces_only($string) {
    if(preg_match("/^['w ]+$]/", $string)) {
        return true;
    } else {
        return false;
    }
}

仅由字母、数字和可选空格组成的字符串