mysql php check form for empty input fields

243
if(empty($_POST['inputEmail'])) {       

    function valid_mail($str) {
    return filter_var($str, FILTER_VALIDATE_EMAIL) ? $str : false;
}

echo 'Please enter a valid email address' . "<br />";

    }
782

Answer

Solution:

if(isset($_POST['submit'])) {
    if(empty($_POST['inputEmail']) || false === filter_var($_POST['inputEmail'], FILTER_VALIDATE_EMAIL)) {
        echo 'Please enter an email address' . "<br />";
    }
    elseif(empty($_POST['inputPostcode'])) {
        echo 'Please enter postcode' . "<br />";
    }
    else {
        // save to db here (no errors occured)
        // return; (or redirect, or whatever)
    }
}

// display form here

You may also use therequired-attribute on required form-fields. You can also use HTML5-input-types, like<input type="mail" /> for client-side checks. Both methods which can be "hacked", but prevents "normal" user to send a not-correctly-filled form. Use PHP's filter_var-function, to validate the mail-address on the server.

975

Answer

Solution:

use a temporary variable:

$validation_error = false;

if($_POST['inputEmail'] == ''){
    echo 'Please enter an email address' . "<br />";
    $validation_error = true;
}

if($_POST['inputPostcode'] == '')
    echo 'Please enter postcode' . "<br />";
    $validation_error = true;
}

// no error occured
if(!validation_error){
    //do stuff
}
507

Answer

Solution:

A better mail validation function could be:

/**
 * Return the mail address if it's valid or false otherwise
 */
function valid_mail($str) {
    $mail_regexp = '/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/';
    preg_match($mail_regexp, $str, $matches);
return strcmp($str, $matches[0]) ? false : $str;
}

or using PHP filter_var (thanks @feela)

function valid_mail($str) {
    return filter_var($str, FILTER_VALIDATE_EMAIL) ? $str : false;
}

People are also looking for solutions to the problem: mysql - How to convert UTF8 to LITHUANIAN_CI_AS in PHP?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.