Jump to content

Please help me VALIDATE Mobile no in php form


rahul19dj

Recommended Posts

Please check the code. I want to validate mobile number of 10 digits and also add a prefix of 0 when I enter into the database.

 

<?php
include ('database_connection.php');

$citystate = $_POST['citystate'];
$serviceprovider = $_POST['serviceprovider'];
$accept = $_POST['accept'];
if (isset($_POST['formsubmitted'])) {
    $error = array();//Declare An Array to store any error message 

if (isset($_POST['checkbox'])){
$mumbai=(in_array("mumbai",$_POST['checkbox']) ? 1 : 0);
$pune=(in_array("pune",$_POST['checkbox']) ? 1 : 0);
$banglore=(in_array("banglore",$_POST['checkbox']) ? 1 : 0);
$mysore=(in_array("mysore",$_POST['checkbox']) ? 1 : 0);	
}	
if($mumbai+$pune+$banglore+$mysore == 0)
{
$error[] ='Please check atleast one SMS center';
}

if($accept != 1)
{
$error[] = 'Please check terms ';
}
# Get the phone number from somewhere
if (empty($_POST['mobileno'])) {//if no name has been supplied 
        $error[] = 'Please Enter a Mobile Number ';//add to array "error"
    }
if (empty($_POST['mobileno'])) {//if no name has been supplied 
        $error[] = 'Please Enter a Mobile Number ';//add to array "error"
    } else {
$mobile = $_POST['mobileno'];//else assign it a variable
/*if( preg_match("^[0-9]{10}", $mobile) ){
        
    }
else {
$error[] = 'Your Mobile No is invalid  ';
} */
}
    if (empty($_POST['fname'])) {//if no name has been supplied 
        $error[] = 'Please Enter a First name ';//add to array "error"
    } else {
        $fname = $_POST['fname'];//else assign it a variable
    }
if (empty($_POST['lname'])) {//if no name has been supplied 
        $error[] = 'Please Enter a Last name ';//add to array "error"
    } else {
        $lname = $_POST['lname'];//else assign it a variable
    }
    if (empty($_POST['email'])) {
        $error[] = 'Please Enter your Email ';
    } else {


        if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
           //regular expression for email validation
            $email = $_POST['email'];
        } else {
             $error[] = 'Your EMail Address is invalid  ';
        }


    }


    if (empty($_POST['passwd1'])) {
        $error[] = 'Please Enter Your Password ';
    } else {
        $password = $_POST['passwd1'];
    }
    if (empty($_POST['passwd2'])) {
        $error[] = 'Please Verify Your Password ';
    } else {
        $password = $_POST['passwd2'];
    }
    if($_POST["passwd1"]!=$_POST["passwd2"])
{
	$error[] = 'Password does not match';
} 

    if (empty($error)) //send to Database if there's no error '

    { //If everything's OK...

        // Make sure the mobile no is available:
        $query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobile'";
        $result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
        if (!$result_verify_mobileno) 
	{//if the Query Failed ,similar to if($result_verify_mobileno==false)
            echo ' Database Error Occured ';
        }

        if (mysqli_num_rows($result_verify_mobileno) == 0) 
	{ // IF no previous user is using this number .


            // Create a unique  activation code:
           //$activation = md5(uniqid(rand(), true));


            $query_insert_user = "INSERT INTO userdtls ( mobileno, serviceprovider, pass, fname, lname, email, citystate, MUM, PUN, BNG, MYS ) VALUES ( '".$mobile."', '".$serviceprovider."', '".$password."', '".$fname."', '".$lname."', '".$email."', '".$citystate."','".$mumbai."', '".$pune."', '".$banglore."', '".$mysore."'  )";

Link to comment
Share on other sites

I've taken the liberty of cleaning your code up a bit. Moved some comments to above the code they described, which is the recommended manner of commenting. Also removed some unnecessary nesting, and added a couple of returns to exit the code early in case of errors. Plus reworked your input validation of the SMS centre detection a bit, which can be improved further as noted in the comment.

Another things I've done is to add the use of an improved "quote_smart ()" (third code block) and sprintf () to the code, to protect against SQL injections.

 

I've added comments prefixed by "CF:" or "TODO:" where I've either wanted to describe why I've done a change, or where you need to do some more coding to complete it.

include ('database_connection.php');

// CF: Create an array of message centres, to use for validation and possibly generation.
// Though, in the latter case I'd go for numerical indices, and used them as the value instead of the actual names.
$msgCentres = array ('mumbai' => true, 'pune' => true, 'banglore' => true, 'mysore' => true);

if (isset ($_POST['formsubmitted'])) {
// Declare an array to store any error message
$error = array (); 

// TODO: Validate input!
$citystate = $_POST['citystate'];
$serviceprovider = $_POST['serviceprovider'];
$accept = $_POST['accept'];

// CF: Check if the checkbox is empty (nothing checked), or if the selected name is not matched
//     in the list of legal SMS centres.
if (empty ($_POST['checkbox'])) {
	$error[] = 'Please check atleast one SMS center';
} else {
	// Loop through all checkboxes, and validate them.
	foreach ($_POST['checkbox'] as $centre) {
		if (!isset ($msgCentres[$centre])) {
			$error[] = 'Invalid SMS center: '.htmlspecialchars ($centre);
			continue;
		}

		// CF: Variable variable, read post for comments on this.
		${$_POST['checkbox']} = 1;
	}
}

if ($accept != 1) {
	$error[] = 'Please check terms ';
}

// Get the phone number from somewhere
if (empty ($_POST['mobileno'])) {
	// if no number has been supplied, add to array "error"
	$error[] = 'Please Enter a Mobile Number ';
// CF: Fixed the RegExp for you. Read post for comments.
} elseif (preg_match ("/^[0-9]{10}\\z/", $mobile) ) {
	// else, if validated, assign it a variable
	$mobile = $_POST['mobileno']; 
} else {
	$error[] = 'Your Mobile No is invalid  ';
}

if (empty ($_POST['fname'])) {
	// if no name has been supplied, add to array "error" 
	$error[] = 'Please Enter a First name '; 
} else {
	// else assign it a variable
	$fname = $_POST['fname'];
}

if (empty ($_POST['lname'])) {  
	// if no name has been supplied, add to array "error"
	$error[] = 'Please Enter a Last name '; 
} else {
	//else assign it a variable
	// TODO: Validate input!
	$lname = $_POST['lname']; 
}

if (empty ($_POST['email'])) {
	$error[] = 'Please Enter your Email ';
} elseif (preg_match ("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
	$email = $_POST['email'];
} else {
	$error[] = 'Your EMail Address is invalid  ';
}

if (empty ($_POST['passwd1'])) {
	$error[] = 'Please Enter Your Password ';
} else {
	$password = $_POST['passwd1'];
}

if (empty ($_POST['passwd2'])) {
	$error[] = 'Please Verify Your Password ';
} else {
	$password = $_POST['passwd2'];
}

if ($_POST["passwd1"] != $_POST["passwd2"]) {
	$error[] = 'Password does not match';
}

if (!empty ($error)) {
	// Add error to output and exit early.
	$error = implode (",<br>\n", $error);

	// TODO: Repopulate form data.
	return false;
}

// Send to Database if there's no error '

// Make sure the mobile no is available:
$query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = ".intval ($mobile);
$result_verify_mobileno = mysqli_query ($dbc, $query_verify_mobileno);

// if the Query Failed ,similar to if($result_verify_mobileno==false)
if (!$result_verify_mobileno) { 
	$error = ' Database Error Occured ';
	return false;
}

// If a previous user is using this number.
if (mysqli_num_rows ($result_verify_mobileno) != 0) {
	// TODO: Add error to output and repopulate form data.
	return false;
} 

// Create a unique  activation code:
//$activation = md5(uniqid(rand(), true));

// CF: Renamed the query to shorten the code a bit, moved to using sprintf() and quote_smart () for security.
$query = "INSERT INTO userdtls (mobileno, serviceprovider, pass, fname, lname, email, citystate, MUM, PUN, BNG, MYS) ".
				"VALUES (%d, %s, %s, %s, %s, %s, %s, %d, %d, %d, %d)";
$query = sprintf ($query, $mobile, qs ($serviceprovider), qs ($password), qs ($fname), qs ($lname),
							qs ($email), qs ($citystate), $mumbai, $pune, $banglore, $mysore);
}

 

Note that variable variables is generally a very bad thing, as they make the code quite a lot harder to read than necessary. This can easily be prevented by using an array with a named index, just like the validation array. I've left it in there for you to fix though, as a little exercise. ;)

 

As for the RegExp itself, there you were missing a couple of thing. First and foremost you had forgotten about the delimiters, aka the slashes, that differentiates between the actual RegExp and it modifiers. Secondly you've forgotten to anchor the RegExp to the end of the string, meaning it'd validate as long as it started with a string of 10 digits.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.