简体   繁体   中英

How to validate form field in php

I have a registration form that has some required field. i want to check if those required fields are filled and if they are filled correctly before i insert in my database.

One of the required field is email, i also want to check if the email entered is a valid email.

My code is below.

Thanks in advance for your help, i really appreciate it.

<?php
include 'config.php';
$tbl_name="citizens"; // Table name
// Get values from form and formatting them as SQL strings
$firstname = mysql_real_escape_string($_POST['firstname']);
$middlename = mysql_real_escape_string($_POST['middlename']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$sex = mysql_real_escape_string($_POST['sex']);
$address = mysql_real_escape_string($_POST['address']);
$employer = mysql_real_escape_string($_POST['employer']);
$posincom = mysql_real_escape_string($_POST['posincom']);
$states = mysql_real_escape_string($_POST['states']);
$agerange = mysql_real_escape_string($_POST['agerange']);
$income = mysql_real_escape_string($_POST['income']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);

// Insert data into mysql 
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful". 
if($result){
echo "You Have Successful Registered";
}else {
echo "Sorry!!! Could Not Register You. All a* fields must be field.";
}
?>
<?php
include 'config.php';
$tbl_name="citizens"; // Table name

$required = array('email');
$errors = array();

foreach($required as $required_fieldname){
    if(!isset($_POST[$required_fieldname]) || empty($_POST[$required_fieldname])){
        $errors[] = 'Sorry!!! Could Not Register You. All a* fields must be field.';
        break;
    }
}

if(isset($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    $errors[] = "That is not a valid email address.";
}

if(count($errors) == 0){
    // Get values from form and formatting them as SQL strings
    $firstname = mysql_real_escape_string($_POST['firstname']);
    $middlename = mysql_real_escape_string($_POST['middlename']);
    $lastname = mysql_real_escape_string($_POST['lastname']);
    $sex = mysql_real_escape_string($_POST['sex']);
    $address = mysql_real_escape_string($_POST['address']);
    $employer = mysql_real_escape_string($_POST['employer']);
    $posincom = mysql_real_escape_string($_POST['posincom']);
    $states = mysql_real_escape_string($_POST['states']);
    $agerange = mysql_real_escape_string($_POST['agerange']);
    $income = mysql_real_escape_string($_POST['income']);
    $email = mysql_real_escape_string($_POST['email']);
    $phone = mysql_real_escape_string($_POST['phone']);

    // Insert data into mysql 
    $sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
    $result= mysql_query($sql);

    // if successfully insert data into database, displays message "Successful". 
    if($result){
        echo "You Have Successfully Registered";
    }else {
        echo "A technical error has occured.";
    }
}
else{
    echo '<strong>ERRORS!</strong><br>';
    foreach($errors as $error){
        echo $error . '<br>';
    }
}
?>

you should validate form before submitting at client side using JavaScript, and alert to user if not filled correctly. Once validated allow it to submit . In other case it is overhead to validate at server and than again send response to user at client end.

For email you can use this (or similar) functions from https://stackoverflow.com/questions/3314493/check-for-valid-email-address to validate email

function isValidEmail($email){
    return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
}

Or

function isValidEmail( $email ){
    return filter_var( $email, FILTER_VALIDATE_EMAIL );
}

For the rest, you can use the following

<?php
    $error = '';

    //put chosen function here
    function isValidEmail( $email ){
        return filter_var( $email, FILTER_VALIDATE_EMAIL );
    }

    //get values and validate each one as required
    $firstname = mysql_real_escape_string($_POST['firstname']);
        if(!$firstname){ $error .= "First name is required<br />"; }

    //repeat for each field
    $email = mysql_real_escape_string($_POST['email']);
        if(!isValidEmail($email)){ $error .= "The email entered is invalid<br />"; }

    //and so on...

    if(!$error){
         //add insert into database code here
    }
    else{
        //display $error however you want e.g....
        echo "<div class=\"error\">$error</div>";
    }
?>
<?php
include 'config.php';
$tbl_name="citizens"; // Table name
// Get values from form and formatting them as SQL strings

//your other fields ...
$email = mysql_real_escape_string($_POST['email']);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ 
$errors = 1;
echo "Please enter a correct email address";
}

//similar approach can be used for other fields..
// this is one of the simplest validating approach


if($errors == 0){
// Insert data into mysql 
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful". 
if($result){
echo "You Have Successful Registered";
}else {
echo "Sorry!!! Could Not Register You. All a* fields must be field.";
}
}
?>

1.) you can use PHP_FILTER for validation.

2.) you can proper check( variable is null or not) before insert the data if variable is null the display error msg otherwish insert..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM