help with validation...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
darkfreaks
Forum Commoner
Posts: 59
Joined: Sat Sep 09, 2006 3:59 pm

help with validation...

Post by darkfreaks »

hey guys so i tried some email validation for my form and it is coded so if it matches a valid email pattern to echo an error but i want it so if its not a valid email adress to echo an error how would i change it?

Code: Select all

<?if($_POST) {if($_POST[email]=="") {echo 'Please enter an email';} elseif(!eregi("^[[]][a-z0-9_.-] @[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {echo "Not a valid email address\n";} else {$_SESSION[OK]++;}}?>
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Erm.. the code already does that. There's a lot of other problems with it though.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

There really is no need to squeeze all the code in just one line.
Array indices that are strings have to be quoted

Code: Select all

echo $arr['abc'];
echo $arr[2];
echo "xyz $arr[abc] zyx";
ereg is deprecated, see http://de2.php.net/manual/en/ref.regex.php

Code: Select all

if( !isset($_POST['email']) || ''===$_POST['email']) {
	echo 'Please enter an email';
}
else if { preg_match($pattern, $email) ) {
	echo 'invalid email address';
}
else {
	echo 'email address ok';
	$_SESSION['OK']++;
}
you might also be interested in http://svn.gna.org/viewcvs/blacknova/tr ... iew=markup
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Wow I must be bored I just started coding...

Code: Select all

/**
 * Tests if the input matches a the basic syntaxical rules of an email address
 *
 * @return bool
 */
function isEmail($value)
{
    return (bool)preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/iu', $value);
}
/**
 * Get a value or default if it is unavailable
 *
 * @param string|int $index of $source
 * @param mixed $default if $source[$index] is blank or null
 * @param array|null $source of data, null uses $_POST
 * @return mixed
 */
function getVar($index, $default = '', $source = null) 
{
    if ($source === null) {
        $source = $_POST;
    }
    if (isset($source[$index]) && !ctype_space($source[$index])) {
        return trim($source[$index]);
    } else {
        return $default;
    }
}
/**
 * Generate an unordered HTML list
 * 
 * @param mixed $data to use a list items
 * @return string
 */
function htmlList($data)
{
    if (empty($data)) {
        return '';
    }
    return '<ul><li>' . implode('</li><li>', (array)$errors) . '</li></ul>';
}
/**
 * Example Usage
 */
if (!empty($_POST)) {
    $errors = array();
    $email = getVar('email');
    if (!isEmail($email)) {
        $errors[] = 'Unspecified or invalid email address';
    }
    echo htmlList($errors);
}
isEmail has been thoroughly tested rest is untested.
darkfreaks
Forum Commoner
Posts: 59
Joined: Sat Sep 09, 2006 3:59 pm

Post by darkfreaks »

i think i will use eregi if i use pregmatch i get the following error:
Warning: preg_match() [function.preg-match]: No ending delimiter '^' found in /home/darkfrea/public_html/order.php on line 94

any ideas on how to fix this?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Just to make sure I'm not going crazy: post what line 94 is.
Z3RO21
Forum Contributor
Posts: 130
Joined: Thu Aug 17, 2006 8:59 am

Post by Z3RO21 »

You can also test to see if an e-mail infact belongs to a working domain. The function you would want to look into would be getmxrr.

And regards to
darkfreaks wrote:i think i will use eregi
read this:
php.net wrote:Note: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().
Happy holidays :)
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

not only faster but
http://de2.php.net/manual/en/ref.regex.php wrote:Tip: PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.
http://de2.php.net/manual/en/ref.regex.php wrote:These regular expression functions are not binary-safe. The PCRE functions are.
darkfreaks wrote:i think i will use eregi if i use pregmatch i get the following error:
Warning: preg_match() [function.preg-match]: No ending delimiter '^' found in /home/darkfrea/public_html/order.php on line 94
any ideas on how to fix this?
pcre uses delimiters to separate the actual pattern from the options.
e.g. /^[a-z]+$/m the actual pattern is ^[a-z]+$ and m is an option
you can also write !^[a-z]+$!m or #^[a-z]+$#m or ....
Z3RO21
Forum Contributor
Posts: 130
Joined: Thu Aug 17, 2006 8:59 am

Post by Z3RO21 »

I use to use ereg but after reading a tutorial on preg_match I never used ereg again. Options rock 8)
darkfreaks
Forum Commoner
Posts: 59
Joined: Sat Sep 09, 2006 3:59 pm

Post by darkfreaks »

Code: Select all

<? if( !isset($_POST['email']) || ''===$_POST['email']) {echo 'Please enter an email';} else if  (preg_match("'/^([-\w]+)(\.[-\w]+)*@([-a-z0-9]+\.?)+\.[a-z]{2,4}$/i'", $email)){echo 'invalid email address';} else { $_SESSION['OK']++; }}?>

the pattern is wrong somewhwere i need a valid pattern :(
darkfreaks
Forum Commoner
Posts: 59
Joined: Sat Sep 09, 2006 3:59 pm

Post by darkfreaks »

Code: Select all

<? if( !isset($_POST['email']) || ''===$_POST['email']) {echo 'Please enter an email';} else if  (preg_match("/^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/", $email))
{echo 'invalid email address';} else { $_SESSION['OK']++; }}?>
ok now my syntax is wrong somewhere either in the above code ot in the following statement in the bottom else code

Code: Select all

}else {
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

What did you just ignore that massive chuck of code I wrote for you?!
darkfreaks
Forum Commoner
Posts: 59
Joined: Sat Sep 09, 2006 3:59 pm

Post by darkfreaks »

eh it works now but i have a problem it always errors with "please enter an email adress" instead of showing the form with "please enter an email adress"
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Over the weekend I wrote an email 'validation' thing...

Code: Select all

function updateEmail(linkId, value) {

	var linkElement = document.getElementById(linkId);
	
	while(linkElement.hasChildNodes() == true) {	
		linkElement.removeChild(linkElement.childNodes[0]);
	}

	var emailFilter = /^.+@.+\..{2,4}$/;

	if (emailFilter.test(value)) {
	
		link = document.createElement('a');
		link.href = 'mailto:'+value;
		link.appendChild(document.createTextNode('Link'));
		link.style.color = 'blue';
		linkElement.appendChild(link);

	} else {

		linkElement.appendChild(document.createTextNode('Link'));
		linkElement.style.color = 'grey';
	
	}

}
To use it you'll need a block of HTML like...

Code: Select all

<div><input id="viewContactEmailAddress" type="text" name="viewContactEmailAddress" style="width: 88%;" onKeyUp="updateEmail('viewContactEmailLink', this.value)"> (<span id="viewContactEmailLink">Link</a></span>)</div>
As you type in the email box the function validates the email address. As soon as it's the correct format it updates (Link) to become a working link to that address. Obviously you could change it to say "Valid" and "Invalid" or something.

You'll still need to validate on the server in case people have JS turned off, but it's a nice addition to any form.
Post Reply