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 />";
}
Asked
Active
Viewed 4,455 times
1

user921334
- 37
- 3
- 8
-
can you post the rest of your code please. – Bruce Sep 06 '11 at 10:06
-
consider to make javascript/client validations – Haim Evgi Sep 06 '11 at 10:08
-
@Haim Evgi - just as an addition, not standalone! – Sascha Galley Sep 06 '11 at 11:55
3 Answers
2
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 the required
-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.

Bill the Lizard
- 398,270
- 210
- 566
- 880

feeela
- 29,399
- 7
- 59
- 71
1
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
}

Sascha Galley
- 15,711
- 5
- 37
- 51
0
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;
}

jbrond
- 727
- 8
- 20
-
That regex would only match email-addresses in ASCII, what about IDN's? See: http://stackoverflow.com/questions/3613589/php-email-validation – feeela Sep 06 '11 at 10:18
-
jbrond thanks for your help so far. I am not sure where to include the email validation function. Where do I include it?? I have update code above. – user921334 Sep 06 '11 at 11:53
-
@user921334 I've updated my answer, to include the validity check. Please revert your question-edit, as your question is no longer available. That is quite confusing, as the answers don't really match the new question. Just append your updated code, instead of replacing it… – feeela Sep 06 '11 at 11:56