在 PHP 文本框中验证数字


Number Validate in Text Box in PHP

我需要验证文本框的值。 文本框用于0123456789格式的客户电话号码(即只有 10 个数字,这也是实时的,这意味着在输入数字时,它不允许用户添加任何字母或特殊符号)

数据通过表单 POST 方法发送到页面(验证.php)。

我想要一个只接受 10 个数字一个接一个,没有字母或字符的函数。

我认为这对你有用:

<html>
<head>
<script type="application/javascript">
  function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
         return true;
      }
</script>
</head>
<body>
    <input type="text" name="tel_num" value="" onkeypress="return isNumberKey(event)" maxlength="10"/>
</body>
</html>
例如您可以使用

preg_match

preg_match('/^[0-9]{10}$/', $_POST['your-value']);

你可以在你的PHP脚本中使用正则表达式,如AVD所述,或者你可以阻止用户提交表单,使用jQuery的验证插件。

.HTML

<form name="contact" id="contact">
    <input name="number" id="number" />
</form>

jQUery

$("#contact").validate({
    rules: {
        number: {
            required: true,
            minlength: 10,
            numeric: true
                }
    },
        messages: {
            number: {
                required: "Enter a phone number",
                minlength: "The phone number is too short",
                numeric: "Please enter numeric values only"
            }
        }
})

更多信息请访问 jQuery/Validation。

试试这个。它验证每个键输入上的条目

.HTML:

<input size="10" maxlength="10" type="text" name="p_len" id="p_len" value="" onkeyup="check(this)" />

Javascript:

function check(o) {
    v=o.value.replace(/^'s+|'s+$/,''); // remove any whitespace
    if(o=='') {
        return;
    }
    v=v.substr(v.length-1);
    if(v.match(/'d/g)==null) {
        o.value=o.value.substr(0,o.value.length-1).replace(/^'s+|'s+$/,'');
    }
}
一旦输入,

它将立即删除非数字输入,长度限制为 10。

希望这有帮助。