PHP Beginner just needs a small amount of help...

Hi guys

I have a working php script that involves entering an eleven digit integer in a HTML form. The script works fine except when something else but an 11 digit integer is entered and then it goes haywire! What is the simplest way to check the form data and return an error message if the form data isn’t in the correct format (ie. an 11 digit integer)?

Any help would be greatly appreciated.

Simon

Off the top of my head the easiest way would be to check only numbers are entered and check the length:

[php]
// get data from form
$number = trim($_POST[‘number’]);

//make sure $number is a number
if(!is_numeric($number)){
$error[] = ‘Only number accepted.’;
}

//check lenght if not equal to 11 throw error
if (strlen($number) != 11) {
$error[] = ‘Number must be 11 digits.’;
}

//check for any errors and show if they are any
if (!empty($error))
{
$i = 0;
while ($i < count($error)){
echo “<div class=“msg-error”>”.$error[$i]."";
$i ++;}
}// close if empty errors
[/php]

Hi Dave

Thanks for the reply.
I have copied and pasted this in above the existing script and it works great - however the remainder of the script still executes despite errors in the form data - how can I stop the script in it’s tracks?

Best regards

Simon

okay when the form is submitted you want the code to check for errors if there are no errors only then carry on:

[php]

<?php //only run when form submitted if(isset($_POST['submit'])){ // get data from form $number = trim($_POST['number']); //make sure $number is a number if(!is_numeric($number)){ $error[] = 'Only number accepted.'; } //check lenght if not equal to 11 throw error if (strlen($number) != 11) { $error[] = 'Number must be 11 digits.'; } //if no errors carry on if(!$error){ //run your code on submission here }//close if no error } //close first if statment //check for any errors and show if they are any if (!empty($error)) { $i = 0; while ($i < count($error)){ echo "
".$error[$i]."
"; $i ++;} }// close if empty errors ?>

form goes here
[/php]

how about:
[php]
$length = strlen($_REQUEST[‘integer’]);
if($length!== 11) {
// display error
}else {

}
[/php]
Hope this helps…

Thanks for all your help ;D ;D

Sponsor our Newsletter | Privacy Policy | Terms of Service