I want to check certain data entry fields to make sure an @ is present and if not show an error. Is this code OK or should I do it a different way. NOTE I only want to check that the field has the @ nothing else. function validate_email($d) { $missing = array('@'); foreach ($missing as $c) if (strpos($d, $c) !== false) return true; return false; } if (!validate_email($_POST['from'])) { echo "Error"; } PHP: Thanks Ian
function validate_email( $email ) { if(preg_match("/@/si", $email)) : return true; endif; } PHP: a more complicated regex would be preferred, if you want something to properly check address formats then holla ....
I believe the 'i' means 'search without case sensitivity' and the 's' means 'allow new lines' (basically). You could also use strpos... something like: $found = strpos( $email, '@' ); Note that because strpos can return '0' (meaning it found the '@' right at the start of the string) you need to compare $found with a triple equal sign against false. So, your function could be: function validate_email( $email ) { $found = strpos( $email, '@' ); if ( $found === FALSE ) { return FALSE; } else { return TRUE; } } PHP:
I use this function to validate emails. function is_valid_email($email) { return preg_match('/^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$/si', $email); } PHP: