Hi, I have just started php. I have a contact form on my website and am using the is_numeric function to check that the phone number entered is a number.

What I want to do is, if the phone number is not a number to output a message just underneath the contact form on the html page telling the user they need to enter a valid number.

Is there a way to do this?

Dani AI

Generated

You can show an inline error right under the form by validating on the server, then re-rendering the same page with an $errors array. Avoid is_numeric() for phones; it will accept values like 1e6 and reject common formats such as +44 20 7123 4567. Treat the phone as a string (agree with @diafol) and validate allowed characters plus a minimum digit count. was on the right track about echoing a message; here is a complete, same-page pattern you can drop in.

<?php
$errors = [];
$phone  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = trim($_POST['phone'] ?? '');

    if ($phone === '') {
        $errors['phone'] = 'Please enter your phone number.';
    } elseif (!preg_match('/^\+?[0-9()\s-]+$/', $phone)) {
        $errors['phone'] = 'Use only digits, spaces, (), - and an optional leading +.';
    } else {
        preg_match_all('/\d/', $phone, $m);
        if (count($m[0]) < 7) {
            $errors['phone'] = 'That looks too short to be a phone number.';
        }
    }

    if (!$errors) {
        // handle success (send email, save, then consider a redirect)
    }
}
?>
<form method="post" action="">
  <label for="phone">Phone</label>
  <input id="phone" name="phone"
         value="<?php echo htmlspecialchars($phone, ENT_QUOTES); ?>"
         pattern="\+?[0-9()\s\-]+"
         title="Digits, spaces, (), -, optional leading +">
  <?php if (!empty($errors['phone'])): ?>
    <p class="error"><?php echo htmlspecialchars($errors['phone'], ENT_QUOTES); ?></p>
  <?php endif; ?>
  <button type="submit">Send</button>
</form>
<style>.error{color:#c00;margin:.25rem 0 0}</style>

This keeps the form "sticky" (user input persists), places the message exactly under the field, and avoids alerts (sorry ) or integer casts () that can drop formatting. If you later need stricter rules, adjust the regex and the minimum digit threshold to fit your audience.

Recommended Answers

All 7 Replies

Try the following:

$phone = (int)$_POST['phone'];
if ($phone==0) {
//invalid phone number
} else {
echo $phone;
}

You can try something like the following where $num is the check that you do to check the phone number:

if (!$num){
	echo "This is not a valid phone number";
  }

Please post the code that you are using for a more detailed explanation.

<html>
<head>
<body onload="msg()">
<script type="text/javascript">

function msg()
{
    alert("wrong pass............................");
}

</script>
</body>
</head>
</html>

if i got your problem right when user submits a from u check if number is proper on same page and if error display an error ?
if yes then try javascript

else cwarn123's solution should do

Member Avatar for Member #120589

Checking a phone number is an integer could be problematic. Some start with 0 (not a problem in itself), some may have () or '-' included. Are these deemed invalid?

Ensure that you don't store them in a DB as integers though - you'll lose the preceeding 0 if there is one.

Checking a phone number is an integer could be problematic. Some start with 0 (not a problem in itself), some may have () or '-' included. Are these deemed invalid?

Ensure that you don't store them in a DB as integers though - you'll lose the preceeding 0 if there is one.

Well the long answer short to that those numbers with () and - will be valid. So what it does is basically filter all non numeric characters then returns the resulting string as an integer when using the (int) parameter and if it's an empty string then it returns 0. If however you want to echo formatted phone numbers this would be rather different and more like the following:

function validate_phone($in) {
$in=str_split($in,1);
$chars=array('0'=>true, '1'=>true, '2'=>true, '3'=>true, '4'=>true, '5'=>true, '6'=>true, '7'=>true, '8'=>true, '9'=>true, '('=>true, ')'=>true, '-'=>true, ' '=>true);
$res='';
foreach ($in AS $chr) {
if (isset($chars[$chr])) {
$res.=$chr;
}
}
return $res;
}

function invalid_phone($in) {
$in=str_split($in,1);
$chars=array('0'=>true, '1'=>true, '2'=>true, '3'=>true, '4'=>true, '5'=>true, '6'=>true, '7'=>true, '8'=>true, '9'=>true);
$res='';
foreach ($in AS $chr) {
if (isset($chars[$chr])) {
$res.=$chr;
}
}
return empty($res);
}
$_POST['phone']='(07) 54261746';
$phone = validate_phone($_POST['phone']);
if (invalid_phone($phone)==true) {
//invalid phone number
} else {
echo $phone;
}

So if your using non formatted numbers use my first example but if however the numbers may be formatted then use the above code.

PHP

<?php
$phone = trim($_POST['phone']);

if(!is_numeric($phone))
    $alert = 'invalid phone number';

?>

Javascript

<input type="text" id="phone" /><br />
<button type="button" id="btn_phone" onclick="control()"></button>




<script>
function IsNumeric(phone) {
   return (phone - 0) == phone && phone.length > 0;
}
function control() {
   var phone = document.getElementById('phone');
   var value = phone.value.replace(/^\s+|\s+$/g,'');
   phone.value = value;
   if (IsNumeric(value) == false)
        alert('invalid phone number');
}
</script>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.