2

I need to validate the value of a text box. The text box is for the customers phone number in the format 0123456789 (ie 10 numbers only and that too live that means while entering number it won't allow user to add any alphabets or special symbols)

The data is sent to a page (validate.php) via a forms POST method.

I want a function that will only accept 10 numbers one after another, no letters or characters.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
viru_d_great
  • 23
  • 1
  • 1
  • 6

4 Answers4

0

you can use preg_match for example

preg_match('/^[0-9]{10}$/', $_POST['your-value']);
Tomas Jancik
  • 1,471
  • 2
  • 12
  • 18
0

You could either use a regex in your PHP script, as AVD stated, or you could prevent the user from submitting the form, using the validate plugin of 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"
            }
        }
})

More info at jQuery/Validation.

Community
  • 1
  • 1
Ahatius
  • 4,777
  • 11
  • 49
  • 79
0

I think this will work for you:

<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>
sephoy08
  • 1,104
  • 7
  • 16
0

Try this. It validates the entry on each key input

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+$/,'');
    }
}

It will remove a non-digit input as soon as it is input and length is limited to 10.

Hope this helps.

web-nomad
  • 6,003
  • 3
  • 34
  • 49